The Web API framework is an Http-oriented communication framework. Compared with WCF, Web API is only designed for Http protocol, and does not have to be as complicated as WCF configuration. Web API development is similar to ASP. net mvc controller development, but relative to the direct use of ASP. net mvc to return Json objects, Web APIs encapsulate data serialization and deserialization, and interfaces and implementations are simpler.
Simply put, if you want to provide Json APIs to browsers and mobile terminals, you should use Web APIs as the communication framework.
Below, I have listed some knowledge points or problems encountered when developing a system using Web APIs.
Data serialization
The Web API framework currently supports two data formats: Json and Xml. Without any configuration, if the Accept in the HttpHeader is specified as accept: application/xml in the Http request, the Web API will automatically serialize the data using xml, otherwise, json serialization is used.
If you do not want to use xml to serialize data, you can use GlobalConfiguration. Configuration. Formatters to configure config. Formatters. Remove (config. Formatters. XmlFormatter ).
Generally, Json serialization is used. Unlike Json serialization of ASP. net mvc, Web APIs use the Newtonsoft. Json framework for serialization. (For example, the JsonMediaTypeFormatter. SerializerSettings attribute is of the Newtonsoft. Json. JsonSerializerSettings type and can be configured directly .)
Json serialization supports serialization of anonymous types, which greatly facilitates developers. For example, we can assemble data and directly return the data at will:
1: [HttpGet]
2: public IEnumerable AllGet()
3: {
4: return new string[] { "Item1", "Item2" }.Select(s => new
5: {
6: Name = s,
7: Code = s,
8: Items = new ArrayList
9: {
10: new { Name = "Item1" },
11: new { Name = "Item2" },
12: new { Name = "Item3" },
13: new { Name = "Item4" },
14: }
15: });
16: }
In addition, the HttpResponseMessage type provided by Web API can be used as the return value, so that developers can make more detailed settings on HttpResponse. In addition, if you want to directly return HttpResponse without modifying the return value type, you can use HttpResponseException to indirectly return an HttpResponseMessage.
Action matching
By default, the Web API framework is based on the Restful architecture mode and ASP. the difference between. net mvc is that it searches for Action in the Controller Based on the Http method (Get, Post, Put, Delete) of the Http request. The rule is: does the Action name start with Get or Post? Mark HttpGet and HttpPost on Action? The method name of the Action is ignored.
For example, CRUD operations on resources by Web APIs are in the following format:
Get/API/models/query all objects
Get/API/models/1000 query an object with the id of 1000
Post/API/models/{id:-1, name: 'name'} Add an object
Put/API/models/{id: 1000, name: 'name'} update a specified object
Delete/API/models/1 delete a specified object
Because the method name is ignored, several methods throw an exception during the call:
In a service-oriented architecture, the underlying entities are often not directly published, so that the client can directly perform CRU operations. Instead, some coarse-grained RPC-based service operations are published. To use the Web API framework, we need to modify the default configuration. For example, you must explicitly specify the action name when calling the client:
1: config.Routes.MapHttpRoute(
2: name: "DefaultApi",
3: routeTemplate: "api/{controller}/{action}/{id}",
4: defaults: new { id = RouteParameter.Optional }
5: );
In this way, because the Action name is explicitly specified, the Web API uses this name to find the corresponding Action method, instead of looking for the corresponding Action according to the HttpMethod convention. For example, the following APIs are called:
1: [HttpGet]
2: public HttpResponseMessage Login(string userName, string password)
3: {
4: return Request.CreateResponse(HttpStatusCode.NotFound);
5: }
Call method:
Get/api/account/login /? Username = hqf@qq.com & password = dsd
POST parameter binding
Compared with ASP. net mvc, Web APIs use new parameter binding classes. Note that only one parameter in the Action parameter list can be deserialized from the Http Post Body. If there is only one parameter in the parameter list and its type is a complex type, the Web API will directly deserialize the Body into an object of this class. If there are multiple parameters, the parameter to be deserialized from the Body must be marked with [FromBodyAttribute].
The related content is complex. You can refer to the following articles:
Http://www.tuicool.com/articles/eQzyEv
Http://weblogs.asp.net/cibrax/archive/2012/08/10/binding-form-data-in-asp-net-web-api.aspx
Good sample code
There is a comprehensive sample code on MSDN:
Http://code.msdn.microsoft.com/ASPNET-Web-API-JavaScript-d0d64dd7
This article is a little bit simple, just to list some points that need attention during the development process. After solving these problems, our system has begun to use Web APIs for development.