ASP. WebAPI Model Binding

Source: Internet
Author: User

In the previous articles, we used the metadata type in the URI to pass the parameter, and the ASP.--model binding is also provided to bind the URI with complex parameters. The model here can be simply understood as a parameter of the target Anction method.

eg

Public figure getfigurefromquerystring ([modelbinder]figure )

{

return figure ;

}

request URL: Http://localhost:4044/api/Figure/GetFigureFromQueryString?FirstName=Bran&LastName=Stack

Results:

{

"FirstName": "Bran",

"LastName": "Stack"

}

(This article, in order to better reflect the results of the binding, all anction return results are request parameters or the consolidated request parameters)

Modelbinder

In the previous article, several references to the URI data are mainly derived from two ways: route,querystring. But the URI only provides a simple underlying data type, in the example above, we find that the parameter becomes a class. Modelbinderattribute provides the ability to convert the underlying data types to complex type data.

[AttributeUsage(attributetargets. Class | AttributeTargets. Parameter, inherited = true, AllowMultiple = false)]

public class modelbinderattribute : parameterbindingattribute

{

}

From the definition we can see that the AttributeUsage of Modelbinder can be seen Modelbinder can be used for types and parameters. I'll list some of the model bindings below.

    1. Simple class

The simple class here refers to the fact that the data refers to the exposed property of the class as the underlying data type. Like the figure class that we've been using before.

public class figure

{

public string FirstName { get; set;}

public string LastName { get; set;}

}

Take the getfigurefromquerystring ([modelbinder]figure figure), the beginning of this article, as an example. Because only one parameter is used in the action. So in the process of transmitting the parameter, we just need to pass Firstname,lastname as QueryString, Modelbinder will convert the figure object.

Http://localhost:4044/api/Figure/GetFigureFromQueryString?FirstName=Bran&LastName=Stack

At the same time, we can also use the route form to pass the parameter:

[Route("Getfigurefromroute/{firstname}/{lastname}")]

Public figure getfigurefromroute (figure )

Url:

Http://localhost:4044/api/Figure/GetFigureFromRoute/Bran/Stack

Of course, and so on, you can also do mixed-pass arguments:

Or based on the Getfigurefromroute Action

We use the following URL to access:

Http://localhost:4044/api/Figure/GetFigureFromRoute/Bran/Stack?FirstName=Robb

Then we will get the result:

{

"FirstName": "Robb",

"LastName": "Stack"

}

This can be seen

The priority of the QueryString parameter is higher than the route parameter

2. Multi-parameter (simple Class)

In the first case we considered a parameter, and now we turn the parameter into two, as follows:

List<figure> method Name (figure A, figure B)

Because this time there are two types of the same parameters, only by the property name can not be distinguished from the parameters. At this time Webapi provided us with a prefix form to differentiate the parameters. Here's how to do a demo with the route:,

[Route("Gettwofigurefromroute/{a.firstname}/{a.lastname}/{b.firstname}/{b.lastname}")]

public List<figure> Gettwofigurefromroute (figure A, figure B)

We make a simple analysis of the route: {parameter name}.{ Property name} as the key for the route

{a.firstname}: FirstName property of Parameter a

{a.lastname}: LastName property of Parameter a

{b.firstname}: FirstName property of parameter B

{b.lastname}: LastName property of parameter B

Accessed using the following URL

Http://localhost:4044/api/Figure/GetTwoFigureFromRoute/Bran/Stack/Robb/Stack

The results are as follows:

[

{

"FirstName": "Bran",

"LastName": "Stack"

},

{

"FirstName": "Robb",

"LastName": "Stack"

}

]

For QueryString forms, it is also very simple to pass the {parameter name}.{ Property name} as the key for QueryString. For example:

public List<figure> gettwofigurefromquerystring (figure A, figure B)

Url:

Http://localhost:4044/api/Figure/GetTwoFigureFromQueryString? a.firstname=bran&a.lastname=stack&b.firstname=robb&B. LastName=stack

will get the same result as the route form

3. Complex classes

Now let's add a Direwolf class attribute Direwolfto the figure, making it a complex class

public class figure

{

public direwolf direwolf { get; set;}

}

public class direwolf

{

public string Name { get; set;}

public string Color { get; set;}

}

In the process of passing parameters obviously we can not assign values to the Direwolf property directly, so we want to split the Direwolf attribute, this time I also need to use the prefix of the way to pass the parameter. As follows:

Public figure getcomplexfigurefromquerystring (figure )

Url:

Http://localhost:4044/api/Figure/GetComplexFigureFromQueryString? Firstname=jon&lastname=snow&direwolf.color=white&direwolf.name=summer

Results:

{

"FirstName": "Bran",

"LastName": "Stack",

"Direwolf": {

"Name": "Summer",

"Color": "White"

}

}

The same is true for route forms:

[Route("Getcomplexfigurefromroute/{firstname}/{lastname}/{direwolf.name}/{direwolf.color}")]

Public figure getcomplexfigurefromroute (figure )

Url:

Http://localhost:4044/api/Figure/GetComplexFigureFromRoute/Bran/Stack/Grey/Summer

The form of multiple parameters can still be processed:

public List<figure> gettwocomplexfigurefromquerystring (figure A, figure b)

Url:

http://localhost:4044/api/figure/gettwocomplexfigurefromquerystring?a.firstname=bran&a.lastname=stack& A.direwolf.color=grey&a.direwolf.name=summer&b.firstname=jon&b.lastname=snow&b.direwolf.color= White&b.direwolf.name=ghost

4. Collection type

Because of the certainty of the length of the collection type, it is still necessary to specify the serial number by prefix, as follows:

public list<int> GetList ([modelbinder] list<int> List)

{

return list;

}

Url:

Http://localhost:4044/api/Figure/GetList? [0]=0&[1]=1&[2]=2&[3]=3

Results:

[

0,

1,

2,

3

]

Attention

The serial number must be a sequential integer starting at 0, or you can only get data before the serial number breaks , such as:

Url:

Http://localhost:4044/api/Figure/GetList? [0]=0&[2]=1&[2]=2&[3]=3

Results:

[

0

]

In addition, the length of the data must be taken into account if you want to take the route form of the method of communication.

5 Dictionary Types

WEBAPI converts the data into a KeyValuePair collection type before the data dictionary type, and then translates it into a dictionary type. So we can use the same way as the collection type when we pass the argument. Such as:

public Dictionary<string, int> getdictionary ([modelbinder] Dictionary<string, int> DIC)

Url:

Http://localhost:4044/api/Figure/GetDictionary? [0]. Key=a&[0]. VALUE=1&[1]. KEY=B&[1]. value=2

Results

{

"A": 1,

"B": 2

}

Source

Github:https://github.com/barlowdu/webapi (Api_4)

ASP. WebAPI Model Binding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.