ASP. NET Web API parameters

Source: Internet
Author: User

Translated from: http://www.c-sharpcorner.com/article/parameter-binding-in-asp-net-web-api/

The main self-study, said is the translation, mainly the meaning of the article recorded, the following into the topic

The Web API is read directly from the URL for the general basic type (primitive type) (Bool,int, double,log,timespan,datetime,guid,string), for complex types, web The API is obtained from the body of the request and needs to use media type.

For this API:

Public httpresponsemessage Put (int  ID, employee employee)  {  ...  ...  }  
View Code

The Web API gets the ID type from the URL and gets the employee type from the body.

Of course this is the default, and we can force the Web API to get from the URL or from the body via the Fromurl and Frombody features.

Fromuri characteristics

 Public class TestData  {      publicstring  Name       {          get;           Set ;      }        Public int Id       {          get;           Set ;      }  }  
View Code
 Public httpresponsemessage Get ([Fromuri] TestData data)   {...       return true );  }  
View Code

This forces the parameter to be fetched from the URL, and the Web API generates the TestData class. URL:http://localhost:24367/api/Employee?Name=Jignesh&Id=10

Can be tested, so there is no problem.

Frombody characteristics

[HttpPost]    Public string name)  {      ...       return true );  }  
View Code

For this API, set the content type: "Application/json" when calling

This setting can be called successfully.

This is not successful, the Web API supports JSON string, does not support JSON objects, so only one parameter in the body is allowed.

Type Converters


You can use the method of type conversion to process the requested data as a string, with the following process:

namespaceWebapitest {usingSystem; usingSystem.ComponentModel; usingSystem.Globalization;  Public classTesttypeconverter:typeconverter { Public Override BOOLCanConvertFrom (ITypeDescriptorContext context, Type sourcetype) {if(SourceType = =typeof(string) ) {returntrue; } returnbase.          CanConvertFrom (context, sourcetype); }             Public Override ObjectConvertFrom (ITypeDescriptorContext context, CultureInfo culture,Objectvalue) {              if(Value is string) {TestData data; if(Testdata.tryparse (string) value, outdata)) {                      returndata; }              }              return Base.          ConvertFrom (context, culture, value); }      }  }  
View Code
Namespacewebapitest {usingSystem.ComponentModel; [TypeConverter (typeof(Testtypeconverter))]  Public classTestData { Public stringName {Get; Set; }           Public intId {Get; Set; }             Public Static BOOLTryParse (strings, outtestdata result) {Result=NULL; varParts = S.split (','); if(Parts. Length! =2)              {                  return false; }                intID; stringName = parts[1]; if(int. TryParse (parts[0], outID)) {result=Newtestdata () {Id= id, Name =name}; return true; }              return false; }      }  }  
View Code

This makes it possible to call the from URL without writing it: http://localhost:24367/api/Employee?data=10,jignesh%20trivedi

 Public httpresponsemessage Get (TestData data)  {      ...       return true );  }  
View Code

Model Binder

another method of processing parameters, implementation of the Imodelbinder interface, only by implementing a method Bindmodel, the following code reads raw data from the route, converts it to testdata, the instance is a simple type conversion, and of course the model binder is not limited to simple types:

namespaceWebapitest {usingSystem; usingSystem.Web.Http.Controllers; usingSystem.Web.Http.ModelBinding; usingSystem.Web.Http.ValueProviders;  Public classCustommodelbinder:imodelbinder {StaticCustommodelbinder () {} Public BOOLBindmodel (Httpactioncontextactioncontext, modelbindingcontextbindingcontext) {if(Bindingcontext.modeltype! =typeof(TestData)) {                  return false; } Valueproviderresult Val=BindingContext.ValueProvider.GetValue (bindingcontext.modelname); if(val = =NULL)              {                  return false; }                stringKey = val. RawValue as string; if(Key = =NULL) {BindingContext.ModelState.AddModelError (Bindingcontext.modeln Ame,"Wrong value type");              Returnfalse; } TestData result=Newtestdata (); vardata =key. Split (newchar[] {','              }); if(Data. Length >1) {result. Id= Convert.ToInt32 (data[0]); Result. Name= data[1]; Bindingcontext.model=result; return true; } bindingContext.ModelState.AddModelError (Bindingcontext.modelname,"cannot convert value to TestData"); return false; }      }  }  
View Code

In addition to registering this binder, we need to generate a Model-binder provider in the configuration. This is the provider:simplemodelbinderprovider that comes with it.

namespaceWebapitest {usingSystem.Web.Http; usingSystem.Web.Http.ModelBinding; usingSystem.Web.Http.ModelBinding.Binders;  Public Static classWebapiconfig { Public Static voidRegister (httpconfigurationconfig) {varProvider =Newsimplemodelbinderprovider (typeof(TestData), Newcustommodelbinder ()); Config. Services.insert (typeof(Modelbinderprovider),0, provider); Config.                Maphttpattributeroutes (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{ID=routeparameter.optional}); }      }  }  
View Code

Call this URL:URI: Http://localhost:24367/api/Employee?data=10,jignesh%20trivedi, There are several ways to use this model Binder To use attributes on parameters:

 Public Httpresponsemessage Get ([Modelbinder (typeof(Custommodelbinder))] TestData data)    {      ...       return true );  }  
View Code

You can also use this feature on a class:

[Modelbinder (typeof(Custommodelbinder))]    Public class TestData   {      //......  }  
View Code

Finished.....

ASP. NET Web API parameters

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.