Core object parsing of Asp. Net WebApi (Part 1), asp. netwebapi

Source: Internet
Author: User
Tags types of filters

Core object parsing of Asp. Net WebApi (Part 1), asp. netwebapi

You need to experience and think about your own life, as well as your knowledge. In a rush, people do not know what they are doing all day long. They seem to be busy every day, but do not know what they are busy. It doesn't matter, as long as we know what we want. In any case, we still have to learn and let ourselves keep moving forward so that we can gradually see our own pursuits and send sighs, who asked the landlord to write novels before? (If you want to read the previous novels of the landlord, you can talk to me privately. The young man who used to have a genuine taste is a pity, but now he is already a hero .)

Don't talk about things. Let's talk about things. What are things? For programmers, of course the code is the case.

In our project development, we often need to use multi-system data interaction and distributed development of some features. In. the main distributed technologies in the NET system are webservice ,. net remoting, MSMQ, and WCF, but today we are introducing Asp. net WebApi, for Asp. net WebApi technology, it is estimated that many people will not be unfamiliar, or often use, because for other distributed technology problems, it will be cumbersome to use, but Asp.. Net WebApi may be easier and quicker. The following describes Asp. Net WebApi technology in detail.

1. Overview of WebApi:

ASP. NET Web API is in. web API Framework built on the. NET Framework, ASP. NET Web API is a programming interface used to operate systems that can be accessed through standard HTTP methods and headers, ASP. NET Web APIs must be based on.. NET 3.5 or later. We are learning ASP. NET Web API, you need to have a deep understanding of the HTTP protocol and web knowledge, so that you are learning ASP. NET Web APIs can be quickly used and applied. Here we will not introduce the basic knowledge of HTTP and Web. If you need to know about HTTP, you can search for it on your own.

ASP. NET Web APIs can be used by various HTTP clients and services provided by web infrastructure.

1. ASP. NET Web APIs have the following features:

(1). It can be used by multiple clients.

(2). Supports standard HTTP methods.

(3). Supports browser-friendly formats. (Supports formats that are easily supported by browsers and any other HTTP clients, such as json and xml)

(4). Supports browser-friendly authentication.

2. software packages required for ASP. NET Web APIs:

(1). System. Net. Http: provides the core HTTP programming model.

(2). System. AspNet. WebApi: provides a reference for installing and hosting all software packages required for installation in ASP. NET.

(3). System. AspNet. WebApi. Core: contains the Core WebApi programming model and runtime components.

(4). System. AspNet. WebApi. Client: contains extensions of the core. net http Client library.

(5). System. AspNet. WebApi. WebHost: contains all runtime components required to host webapis in ASP. NET runtime.

For ASP. NET Web API simple demo, security authentication, exception handling, content negotiation, boarding method, error handling, etc, if there is time, the blogger will explain the content separately.

Ii. Overview of the WebApi Routing Mechanism:

For ASP. NET Web API routing introduction is relatively simple, because it is not difficult for people familiar with mvc, and the focus of this blog is not here, so here we will only give a brief introduction. ASP. NET WebAPI uses the HTTP method instead of the URI path to select the action. You can also use the WebAPI of MVC-style routing.

In ASP. NET Web APIs, a controller is a class that processes HTTP requests. The public methods of the controller are called Action methods or simple actions. When the Web API framework receives a request, the request is routed to an action. The route table used by the framework to determine which action to call. The following code:

routes.MapHttpRoute(    name: "API Default",    routeTemplate: "api/{controller}/{id}",    defaults: new { id = RouteParameter.Optional });

When setting a WebAPI route, we have tried our best to avoid conflict with the AspNet Mvc route. This is a precaution in ASP. NET Web API.

The routing mechanism of ASP. NET Web APIs is as follows:

(1) Find the controller and the Network API controls the variable {} of the controller value.

(2) Network API looks at the HTTP Method for the action to be searched, and then finds an action name with the HTTP method name. For example, you can use a GET request or WebAPI to search for an action starting with "GetContact" or "GetAllContacts. This Convention applies only to GET, POST, PUT, and DELETE methods. You can enable other HTTP methods by using properties on the controller.

(3). Other placeholder variables in the routing template, such as {ID}, are mapped to the parameters of the action.

The routing mechanism of ASP. NET Web APIs is explained so much. You can learn more about it by yourself.

3. Core WebApi object ApiController:

In our webapi project, there is a WebApiConfig class under the top-level directory App_Start. This class contains only one method Register, which is called by the Application_Start method in Global. asax. The Code is as follows:


The routing ing method is only an extension method. To learn more about the "extension method", read the following: Routing.

Here we will focus on the ApiController class.

ApiController is the parent class of the ValuesController class and is the core class of the entire ASP. NET Web API. It inherits this class and can be used to create an ASP. NET Web API controller. The public static members in the ApiController class (shared in Visual Basic) are thread-safe, and no instance Member can guarantee thread-safe. The following describes the tasks of ApiController in ASP. NET Web APIs:

(1) Select and run an operation method on the Controller class.

(2) convert each element of the HTTP request message to a parameter of the controller operation method, and convert the return value of the operation method to a valid HTTP response body. (The data format of the HTTP response body can be negotiated between the client and the server. The default format is json. The benefits of json format are not described here, however, I personally think the json format should be the focus of future data formats .)

(3). run various filters. These filters can be configured for the operation method, controller, or global.

(4). Provide appropriate context states for the operation methods of the controller class.

The above is a brief introduction to the role of the ApiController class. Let's take a look at the implementation code below.

First, let's preview the methods and attributes of the ApiController class:

1. Attribute summary:

ActionContext: Get the operation context;

Configuration and ControllerContext: Get the HttpConfiguration object of the current ApiController;

ModelState: obtains the model state after model binding;

Request: gets or sets the HttpRequestMessage of the current ApiController;

RequestContext: Get the request context;

Url: used to generate a URL pointing to another API;

User: returns the current subject associated with the request;

2. method summary:

ExecuteAsync (): executes an HTTP operation asynchronously. This method is a virtual method and can be rewritten in a subclass;

Validate <TEntity> (): verifies the given entity and adds the validation error to the model state with an empty prefix;

Initialize (): Use the specified controllerContext to Initialize the System. Web. Http. ApiController instance;

BadRequest (): creates an InvalidModelStateResult model with the specified state.

Created (): Create a CreatedNegotiatedContentResult '1 (201 indicates that it has been Created) with the specified value.

Redirect (): Creates a redirection result with a specified value (302 Found ).

ResponseMessage (): Create a ResponseMessageResult with the specified response.

3. Detailed code introduction:

The ApiController class implements the IHttpController and IDisposable interfaces. To create a controller in ASP. NET Web API, you only need to implement the IHttpController interface. Let's take a look at the implementation code of the IHttpController interface:

// Indicates the HTTP controller public interface IHttpController {// executes the Controller for synchronization. // Parameter: controllerContext: current context of the test controller. CancellationToken: indicates a notification that the operation is canceled. // Return result: controller. Task <HttpResponseMessage> ExecuteAsync (HttpControllerContext controllerContext, CancellationToken cancellationToken );}

You can see that this interface only has one method ExecuteAsync (). This method is an Asynchronous Method. HttpControllerContext indicates an HTTP request object, and CancellationToken indicates a cancel token assigned to the HTTP operation by passing a message, task <HttpResponseMessage> shows that this method returns an asynchronous HTTP object. Let's take a look at the implementation code of the ApiController squadron class:

/// <Summary> /// asynchronously executes a single HTTP operation. /// </Summary> /// <returns> /// the newly started task. /// </Returns> /// <param name = "controllerContext"> controller context for a single HTTP operation. </Param> <param name = "cancellationToken"> unmark an HTTP operation. </Param> public virtual Task <HttpResponseMessage> ExecuteAsync (HttpControllerContext controllerContext, CancellationToken cancellationToken) {if (this. _ initialized) throw Error. invalidOperation (SRResources. cannotSupportSingletonInstance, new object [2] {(object) typeof (ApiController ). name, (object) typeof (IHttpControllerActivator ). name}); this. initialize (controllerContext); if (this. request! = Null) HttpRequestMessageExtensions. RegisterForDispose (this. Request, (IDisposable) this); ServicesContainer services = controllerContext. ControllerDescriptor. Configuration. Services;
// Select the action HttpActionDescriptor actionDescriptor = ServicesExtensions. GetActionSelector (services). SelectAction (controllerContext); this. ActionContext. ActionDescriptor = actionDescriptor; if (this. Request! = Null) HttpRequestMessageExtensions. SetActionDescriptor (this. Request, actionDescriptor); FilterGrouping filterGrouping = actionDescriptor. GetFilterGrouping ();
// Obtain the action filter IActionFilter [] actionFilters = filterGrouping. ActionFilters;
// Obtain the authorization filter IAuthenticationFilter [] authenticationFilters = filterGrouping. AuthenticationFilters; IAuthorizationFilter [] authorizationFilters = filterGrouping. AuthorizationFilters;
// Obtain the exception filter IExceptionFilter [] exceptionFilters = filterGrouping. predictionfilters; IHttpActionResult innerResult = (IHttpActionResult) new ActionFilterResult (actionDescriptor. actionBinding, this. actionContext, services, actionFilters); if (authorizationFilters. length> 0) innerResult = (IHttpActionResult) new AuthorizationFilterResult (this. actionContext, authorizationFilters, innerResult); if (authenticationFilters. length> 0) innerResult = (IHttpActionResult) new AuthenticationFilterResult (this. actionContext, this, authenticationFilters, innerResult); if (exceptionFilters. length> 0) {IExceptionLogger logger = ExceptionServices. getLogger (services); IExceptionHandler handler = ExceptionServices. getHandler (services); innerResult = (IHttpActionResult) new ExceptionFilterResult (this. actionContext, exceptionFilters, logger, handler, innerResult);} return innerResult. executeAsync (cancellationToken );}

The above implementation code shows that there are three types of filters: IActionFilter, IAuthenticationFilter, and IExceptionFilter. After obtaining the message request, this method initializes the message and request and calls HttpRequestMessageExtensions. registerForDispose (this. request, (IDisposable) this method is registered, which filters the Request information.

Let's take a look at the specific code of the Request and RequestContext attributes:

/// <Summary> /// obtain or set the HttpRequestMessage of the current ApiController. /// </Summary> /// <returns> /// HttpRequestMessage of the current ApiController. /// </Returns> public HttpRequestMessage Request {get {return this. controllerContext. request;} set {if (value = null) throw Error. propertyNull (); HttpRequestContext requestContext1 = HttpRequestMessageExtensions. getRequestContext (value); HttpRequestContext requestContext2 = this. requestContext; if (requestContext1! = Null & requestContext1! = RequestContext2) throw new InvalidOperationException (SRResources. requestContextConflict); this. controllerContext. request = value; HttpRequestMessageExtensions. setRequestContext (value, requestContext2); RequestBackedHttpRequestContext httpRequestContext = requestContext2 as RequestBackedHttpRequestContext; if (httpRequestContext = null) return; httpRequestContext. request = value ;}/// <summary> /// Obtain the request context. /// </Summary> /// <returns> /// request context. /// </Returns> public HttpRequestContext RequestContext {get {return this. controllerContext. requestContext;} set {if (value = null) throw Error. propertyNull (); HttpRequestContext requestContext1 = this. controllerContext. requestContext; HttpRequestMessage request = this. request; if (request! = Null) {HttpRequestContext requestContext2 = HttpRequestMessageExtensions. GetRequestContext (request); if (requestContext2! = Null & requestContext2! = RequestContext1 & requestContext2! = Value) throw new InvalidOperationException (SRResources. RequestContextConflict); HttpRequestMessageExtensions. SetRequestContext (request, value);} this. ControllerContext. RequestContext = value ;}}

The Request and RequestContext attributes are used to set and obtain the HttpRequestMessage object and RequestContext object respectively,

In addition to the HTTP method, the ASP. NET Web API can select an operation method based on other elements of the request. The ASP. NET Web API framework supports Binding Request elements to operation method parameters. Convert the HTTP response value to the appropriate HTTP Response Message Body.

Iv. Summary:

The above is for ASP. NET Web API background and usage, as well as ASP. NET Web API core object. Next, we will introduce the parsing of HttpRequestMessage, HttpResponseMessage, HttpClient, and other three objects. If there are any deficiencies or errors in this article, I hope you can correct them more.

Related Article

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: 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.