ASP. NET Web API: host (Hosting), apihosting

Source: Internet
Author: User
Tags web hosting

ASP. NET Web API: host (Hosting), apihosting

Reference page:

Http://www.yuanjiaocheng.net/webapi/test-webapi.html

Http://www.yuanjiaocheng.net/webapi/web-api-controller.html

Http://www.yuanjiaocheng.net/webapi/config-webapi.html

Http://www.yuanjiaocheng.net/webapi/web-api-route.html

Http://www.yuanjiaocheng.net/webapi/parameter-binding.html

ASP. NET Web API processing architecture introduces ASP. NET Web APIs are composed of three layers: hosting, message handler pipeline, and controller handling. This article mainly introduces the host (Hosting ): including ASP. the self-host SelfHosting of the Web Hosting and WCF stack on the NET classic pipeline.

Web Hosting on ASP. NET classic Pipeline

1. ASP. NET routing allows you to use URLs that do not need to be mapped to specific files on the website. Because the URL does not need to be mapped to a file, you can describe user operations to make it easier for users to understand the URL. routes are equally important on ASP. NET Web APIs. On the ASP. NET platform, Routes are added to the routing table through the static attribute Routes of RouteTable. For example, the following code is the default route defined by the ASP. net mvc Project template:

Protected void Application_Start ()
{
RegisterRoutes (RouteTable. Routes );
}

Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");

Routes. MapRoute (
"Default", // Route name
"{Controller}/{action}/{id}", // URL with parameters
New {controller = "Home", action = "Index", id = UrlParameter. Optional}
);
}

Most of the routing logic is the pipeline event PostResolveRequestCache appended by UrlRoutingModule to ASP. NET. For each Http request, this module matches the routing rules in the routing set. If there is a match, then:

  • Get a Route handler from route Data
  • Obtain an Http Handler that implements the IHttpHandler interface from Route Handler.
  • Finally, the current request context is mapped to the preceding Http handler.

Therefore, the request is sent to this processor at the end of the ASP. NET pipeline.

2. Integrate Web APIs. When the host and ASP. NET are configured in a single piece of HttpConfiguration object, they are accessed through the static attribute GlobalConfiguration. Configuration. The Web API also defines several RouteCollection extension methods, called MapHttpRoute, to define the configuration of Web APIs. See the following example:

HttpConfiguration config = GlobalConfiguration. Configuration;
Config. Routes. MapHttpRoute ("default", "{controller}/{id}", new {id = UrlParameter. Optional });
// Other configuration settings

The above code mainly provides two functions:

  • The static attribute GlobalConfiguration. Configuration is used to obtain the Configuration, pointing to the global RouteTable. Routes route set.
  • Use the MapHttpRoute Extension Method to add route configurations.

The Route Handler added to the Route set through the MapHttpRoute extension method is HttpControllerRouteHandler, matching the request added using MapHttpRoute. The related Route Handler returns a new processor type HttpControllerHandler, which implements asynchronousIAsyncHttpHandlerThis processor uses the route data initialization and contains matching information.

When HttpControllerHandler'sBeginProcessRequestMethod to perform the following actions:

  • Create an HttpRequestMessage instance from the current HttpContext
  • Use the Configuration of GlobalConfiguration. Configuration to create an HttpServer, and then push the new HttpRequestMessage instance to the server pipeline.

After the HttpServer obtains the request, it enters a new stage of host processing (new Web API pipeline ). The following figure summarizes the routing process and distributes it to the HttpServer instance (information processing pipeline ).

Self-host SelfHosting Based on WCF Stack

The Web host on ASP. NET is described above. Next we will introduce the self-host SelfHosting Based on the WCF stack. Let's take a look at a piece of Self-host code:

Var config = new HttpSelfHostConfiguration ("http: // localhost: 8080 ");
Config. Routes. MapHttpRoute ("default", "{controller}/{id }",
New {id = RouteParameter. Optional });
Var server = new HttpSelfHostServer (config );
Server. OpenAsync (). Wait ();
Console. WriteLine ("Server is opened ");

HttpSelfHostServer inherits from HttpServer and uses HttpSelfHostConfiguration as the configuration class. The class diagram structure is as follows:

The WCF stack used in HttpSelfHostServer obtains messages from the transmission media and pushes them to the upper-layer message processing pipeline. The following section briefly introduces the high-level architecture of WCF and the features of Web API self-hosting.

WCF Architecture

The WCF architecture is divided into two layers: Channel Stack and Service Model. For details, refer:

The lower channel stack layer is composed of a bunch of channels and behavior similar to the classic network protocol stack. There are two types of channels: transmission channels and Protocol channels. The transmission channel consists of interfaces and transmission media (such as TCP, MSMQ, and HTTP) (Yes, I Know That HTTP is not just a transmission protocol), that is, receiving and transmitting messages. The information channel traffic process of the Protocol is superimposed. A typical use case of adding a protocol channel digital signature on the sender and the person who verifies the signature on the receiving side. Transmission Channel, which uses encoder to convert byte streams and information transport media byte instances.

The upper-layer Service Model executes messages and method calls. The processed items are as follows:

  • Converts received messages to parameter sequences.
  • Obtain the used service instance
  • Select the method to call
  • Select a thread to process the call.

However, HttpSelfHostServer does not use the Service Model layer. Instead, it directly consumes messages obtained from the transport channel stack. The transport channel stack layer uses Binding for organization, as shown in:

Binding is a set of ordered Binding elements. Each Element describes a channel or encoder. The first Binding Element describes the upper-layer channel, and the last Binding Element describes the underlying channel. In short, this is a transmission channel.

HttpSelfHostServer and HttpSelfHostConfiguration

In the internal HttpSelfHostserver. OpenAsync method, an HttpBinding instance is created and configured based on the HttpSelfHostConfiguration instance attributes. Then he uses this Binding to asynchronously create a WCF transport stack, and he also createsPumpPushing a message into this stack, converting it to an HttpRequestMessage instance, and pushing a new request to HttpServer is the message processing process:

When using a self-host, most of the wcf http binding constraints and settings are available. The HttpBinding instance created in the configuration can be created in two ways. The first method is to use the HttpSelfHostConfiguration attribute, such as MaxBufferSize and TransferMode, which are used to internally create HttpBinding instances. The second method is to create a subclass of HttpSelfHostConfiguration and then override the OnConfigureBinding method, this method has the opportunity to modify the binding configuration before creating the channel stack.

ASP. NET WebAPI Hosting Techniques http://www.codeproject.com/Articles/555923/ASP-NET-WebAPI-Hosting-Techniques

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