ASP. NET web API Tutorial: 5.1 HTTP message processor

Source: Internet
Author: User


Note:This article is part of the [ASP. NET web API series tutorial]. If this is the first time you read this series of tutorials, read the previous content first.


5.1 HTTP message handlers
5.1 HTTP message processor


This article cited from: http://www.asp.net/web-api/overview/working-with-http/http-message-handlers



By Mike Wasson | February 13,201 2
Author: Mike Wasson | Date:



A message handler is a class that reads es an HTTP request and returns an HTTP response. Message handlers derive from the abstractHttpmessagehandlerClass.
A message processor is a class that receives HTTP requests and returns HTTP responses. Message processor derived fromHttpmessagehandlerClass.



Typically, a series of message handlers are chained together. the first handler handles es an HTTP request, does some processing, and gives the request to the next handler. at some point, the response is created and goes back up the chain. this pattern is calledDelegatingHandler.
Typically, a series of message processors are linked together. The first processor receives the HTTP request, performs some processing, and delivers the request to the next processor. At a point, create a response and return it along the chain. This mode is calledDelegateProcessor (DelegatingHandler) (5-1 ).



Figure: Request: request, delegating handler: Delegate processor, inner handler: internal processor, response: Response



Figure 5-1. message processor chain


Server-side message handlers
Server Message Processor


On the server side, the web API pipeline uses some built-in message handlers:
On the server side, the web API pipeline uses some built-in message processors:


    • HttpserverGets the request from the host.
      HttpserverObtain the request from the host.
    • HttproutingdispatcherDispatches the request based on the route.
      Httproutingdispatcher(HTTP route distributor) distributes requests based on routes.
    • HttpcontrollerdispatcherSends the request to a web API controller.
      Httpcontrollerdispatcher(HTTP controller distributor) sends requests to a web API controller.


You can add M handlers to the pipeline. message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions ). for example, a message handler might:
You can add a custom processor to the MPs queue. The message processor is useful for cross-attention of operations on the HTTP message layer (rather than on the Controller action. For example, a message processor can:


    • Read or modify request headers.
      Read or modify the request header.
    • Add a response header to responses.
      Add a response header to the response.
    • Validate requests before they reach the controller.
      Verify the request before it reaches the controller.


This digoal shows two custom handlers inserted into the pipeline:
Displays the two custom processors inserted into the pipeline (see Figure 5-2 ):



Figure 5-2. Server Message Processor



On the client side, httpclient also uses message handlers. For more information, see httpclient message handlers.
On the client, httpclient also uses a message processor. For more information, see "HTTP message processor" (section 3.4-Translator's note in this series of tutorials ).


Custom message handlers
Custom message processor


To write a custom message handler, derive fromSystem. net. http. delegatinghandlerAnd overrideSendasyncMethod. This method has the following signature:
To write a custom message processor, you must useSystem. net. http. delegatinghandlerAnd rewriteSendasyncMethod. This method has the following signatures:


Task <HttpResponseMessage> SendAsync (
    HttpRequestMessage request, CancellationToken cancellationToken);
The method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:
This method takes HttpRequestMessage as an input parameter and returns an HttpResponseMessage asynchronously. A typical implementation does the following:

Process the request message.
Process the request message.
Call base.SendAsync to send the request to the inner handler.
Call base.SendAsync to send the request to the internal processor.
The inner handler returns a response message. (This step is asynchronous.)
The internal processor returns a response message. (This step is asynchronous.)
Process the response and return it to the caller.
Processes the response and returns it to the caller.
Here is a trivial example:
Here's a low-value example:

public class MessageHandler1: DelegatingHandler
{
    protected async override Task <HttpResponseMessage> SendAsync (
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Debug.WriteLine ("Process request");
        // Call the inner handler.
        // Call the internal processor.
        var response = await base.SendAsync (request, cancellationToken);
        Debug.WriteLine ("Process response");
        return response;
    }
}
The call to base.SendAsync is asynchronous. If the handler does any work after this call, use the await keyword, as shown.
The call to base.SendAsync is asynchronous. If the processor has work to do after the call, use the await keyword, as shown above.

A delegating handler can also skip the inner handler and directly create the response:
The delegate processor can also skip the internal processor and create the response directly:

public class MessageHandler2: DelegatingHandler
{
    protected override Task <HttpResponseMessage> SendAsync (
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Create the response.
        // Create a response.
        var response = new HttpResponseMessage (HttpStatusCode.OK)
        {
            Content = new StringContent ("Hello!")
        };

        // Note: TaskCompletionSource creates a task that does not contain a delegate.
        // Note: TaskCompletionSource creates a task without a delegate.
        var tsc = new TaskCompletionSource <HttpResponseMessage> ();
        tsc.SetResult (response); // Also sets the task state to "RanToCompletion"
                                      // also set this task to "RanToCompletion (completed)"
        return tsc.Task;
    }
}
If a delegating handler creates the response without calling base. SendAsync, the request skips the rest of the pipeline. This can be useful for a handler that validates the request (creating an error response).
If the delegate processor did not call base.SendAsync to create a response, the request skips the rest of the pipeline (shown in Figure 5-3). This may be useful for a processor that validates a request (creating an error message).

Figure 5-3. Skipped Processors

Adding a Handler to the Pipeline
Add a processor to the pipeline
To add a message handler on the server side, add the handler to the HttpConfiguration.MessageHandlers collection. If you used the "ASP.NET MVC 4 Web Application" template to create the project, you can do this inside the WebApiConfig class:
To add a message handler on the server side, you need to add the handler to the HttpConfiguration.MessageHandlers collection. If you use the "ASP.NET MVC 4 Web Application" template to create your project, you can do this in the WebApiConfig class:

public static class WebApiConfig
{
    public static void Register (HttpConfiguration config)
    {
        config.MessageHandlers.Add (new MessageHandler1 ());
        config.MessageHandlers.Add (new MessageHandler2 ());

        // Other code not shown ...
    }
}
Message handlers are called in the same order that they appear in MessageHandlers collection. Because they are nested, the response message travels in the other direction. That is, the last handler is the first to get the response message.
Message handlers are called in the order they appear in the MessageHandlers collection. Because they are embedded, the response message runs in the opposite direction, that is, the last processor gets the response message first.

Notice that you don't need to set the inner handlers; the Web API framework automatically connects the message handlers.
Note that no internal handlers need to be set; the Web API framework will automatically connect to these message handlers.

If you are self-hosting, create an instance of the HttpSelfHostConfiguration class and add the handlers to the MessageHandlers collection.
If it's "self-hosted" (Section 8.1 of this tutorial series — translator's note), you need to create an instance of the HttpSelfHostConfiguration class and add the handler to the MessageHandlers collection.

var config = new HttpSelfHostConfiguration ("http: // localhost");
config.MessageHandlers.Add (new MessageHandler1 ());
config.MessageHandlers.Add (new MessageHandler2 ());
Now let's look at some examples of custom message handlers.
Now let's look at some examples of custom message handlers.

Example: X-HTTP-Method-Override
Example: X-HTTP-Method-Override
X-HTTP-Method-Override is a non-standard HTTP header. It is designed for clients that cannot send certain HTTP request types, such as PUT or DELETE. Instead, the client sends a POST request and sets the X-HTTP-Method -Override header to the desired method. For example:
X-HTTP-Method-Override is a non-standard HTTP header. This is designed for clients that cannot send certain HTTP request types (such as PUT or DELETE). Therefore, the client can send a POST request and set X-HTTP-Method-Override to the desired method (that is, for a client that cannot send a PUT or DELETE request, you can have it send a POST request and then use X -HTTP-Method-Override rewrites this POST request as a PUT or DELETE request — Translator's Note). E.g:

X-HTTP-Method-Override: PUT
Here is a message handler that adds support for X-HTTP-Method-Override:
Here is a message server with X-HTTP-Method-Override support added:

public class MethodOverrideHandler: DelegatingHandler
{
    readonly string [] _methods = {"DELETE", "HEAD", "PUT"};
    const string _header = "X-HTTP-Method-Override ";

    protected override Task <HttpResponseMessage> SendAsync (
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Check for HTTP POST with the X-HTTP-Method-Override header.
        // Check HTTP POST with X-HTTP-Method-Override header.
        if (request.Method == HttpMethod.Post && request.Headers.Contains (_header))
        {
            // Check if the header value is in our methods list.
            // check if the header value is in our method list
            var method = request.Headers.GetValues (_header) .FirstOrDefault ();
            if (_methods.Contains (method, StringComparer.InvariantCultureIgnoreCase))
            {
                // Change the request method.
                // modify the request method
                request.Method = new HttpMethod (method);
            }
        }
        return base.SendAsync (request, cancellationToken);
    }
}
In the SendAsync method, the handler checks whether the request message is a POST request, and whether it contains the X-HTTP-Method-Override header. If so, it validates the header value, and then modifies the request method. Finally, the handler calls base.SendAsync to pass the message to the next handler.
In the SendAsync method, the processor checks whether the request message is a POST request and whether it contains an X-HTTP-Method-Override header. If it is, it validates the header value and then modifies the request method. Finally, the processor calls base.SendAsync to pass the message to the next server.

When the request reaches the HttpControllerDispatcher class, HttpControllerDispatcher will route the request based on the updated request method.
When the request reaches the HttpControllerDispatcher class, the HttpControllerDispatcher will route the request according to the updated request method.

Example: Adding a Custom Response Header
Example: Adding a custom response header
Here is a message handler that adds a custom header to every response message:
Here is a message handler that adds a custom header to each response message:

// .Net 4.5
public class CustomHeaderHandler: DelegatingHandler
{
    async protected override Task <HttpResponseMessage> SendAsync (
            HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.SendAsync (request, cancellationToken);
        response.Headers.Add ("X-Custom-Header", "This is my custom header.");
        return response;
    }
}
First, the handler calls base.SendAsync to pass the request to the inner message handler. The inner handler returns a response message, but it does so asynchronously using a Task <T> object. The response message is not available until base.SendAsync completes asynchronously.
First, the handler calls base.SendAsync to pass the request to the internal message handler. The internal processor returns a response message, but it does this asynchronously with the Task <T> object. The response message will not be available until base.SendAsync completes asynchronously.

This example uses the await keyword to perform work asynchronously after SendAsync completes. If you are targeting .NET Framework 4.0, use the Task.ContinueWith method:
This example uses the await keyword to execute tasks asynchronously after SendAsync completes. If your target framework is .NET Framework 4.0, use the Task.ContinueWith method:

public class CustomHeaderHandler: DelegatingHandler
{
    protected override Task <HttpResponseMessage> SendAsync (
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return base.SendAsync (request, cancellationToken) .ContinueWith (
            (task) =>
            {
                HttpResponseMessage response = task.Result;
                response.Headers.Add ("X-Custom-Header", "This is my custom header.");
                return response;
            }
        );
    }
}
Example: Checking for an API Key
Example: Checking API keys
Some web services require clients to include an API key in their request. The following example shows how a message handler can check requests for a valid API key:
Some web services require the client to include an API key in their request. The following example demonstrates how a message handler checks a request against a valid API key:

public class ApiKeyHandler: DelegatingHandler
{
    public string Key {get; set;}

    public ApiKeyHandler (string key)
    {
        this.Key = key;
    }

    protected override Task <HttpResponseMessage> SendAsync (
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (! ValidateKey (request))
        {
            var response = new HttpResponseMessage (HttpStatusCode.Forbidden);
            var tsc = new TaskCompletionSource <HttpResponseMessage> ();
            tsc.SetResult (response);
            return tsc.Task;
        }
        return base.SendAsync (request, cancellationToken);
    }

    private bool ValidateKey (HttpRequestMessage message)
    {
        var query = message.RequestUri.ParseQueryString ();
        string key = query ["key"];
        return (key == Key);
    }
}
This handler looks for the API key in the URI query string. (For this example, we assume that the key is a static string. A real implementation would probably use more complex validation.) If the query string contains the key, the handler passes the request to the inner handler.
The processor looks for the API key in the URI query string (for this example, we assume the key is a static string. A real implementation might use more complex validation.) If the query string contains this key, the Processing passes the request to the internal processor.

If the request does not have a valid key, the handler creates a response message with status 403, Forbidden. In this case, the handler does not call base.SendAsync, so the inner handler never receives the request, nor does the controller. Therefore, the controller can assume that all incoming requests have a valid API key.
If the request does not have a valid key, the processor creates a response message with a status of "403-Access Denied". In this case, the processor will not call base.SendAsync, so the internal processing will not receive the request, and the controller will not receive the request. Therefore, the controller can assume that all input requests have a valid API key.

If the API key applies only to certain controller actions, consider using an action filter instead of a message handler. Action filters run after URI routing is performed.
If API keys are used only for certain controller actions, consider using action filters instead of message handlers. Action filtering runs after URI routing is complete.

Per-Route Message Handlers
Single route message processor
Handlers in the HttpConfiguration.MessageHandlers collection apply globally.
The handlers in the HttpConfiguration.MessageHandlers collection are used globally.

Alternatively, you can add a message handler to a specific route when you define the route:
Alternatively, when defining a route, add a message handler to a specific route:

public static class WebApiConfig
{
    public static void Register (HttpConfiguration config)
    {
        config.Routes.MapHttpRoute (
            name: "Route1",
            routeTemplate: "api / {controller} / {id}",
            defaults: new {id = RouteParameter.Optional}
        );

        config.Routes.MapHttpRoute (
            name: "Route2",
            routeTemplate: "api2 / {controller} / {id}",
            defaults: new {id = RouteParameter.Optional},
            constraints: null,
            handler: new MessageHandler2 () // per-route message handler
        );
        config.MessageHandlers.Add (new MessageHandler1 ()); // global message handler
    }
}
In this example, if the request URI matches "Route2", the request is dispatched to MessageHandler2. The following diagram shows the pipeline for these two routes:
In this example, if the requested URI matches "Route2", the request is dispatched to MessageHandler2. Figure 5-4 shows the two routing pipelines:

Figure 5-4. Single Route Message Processor

Notice that MessageHandler2 replaces the default HttpControllerDispatcher. In this example, MessageHandler2 creates the response, and requests that match "Route2" never go to a controller. This lets you replace the entire Web API controller mechanism with your own custom endpoint.
Note that MessageHandler2 replaces the default HttpControllerDispatcher. In this example, MessageHandler2 creates a response, and requests matching "Route2" do not reach the controller. This allows you to replace the entire Web API controller mechanism with your own custom endpoint.

Alternatively, a per-route message handler can delegate to HttpControllerDispatcher, which then dispatches to a controller.
Alternatively, a single-routed message handler can be delegated to HttpControllerDispatcher, which then dispatches it to the controller (shown in Figure 5-5).

Figure 5-5. Delegating a message handler to HttpControllerDispatcher

The following code shows how to configure this route:
The following code shows how to configure this route:

// List of delegating handlers.
// Delegate handler list
DelegatingHandler [] handlers = new DelegatingHandler [] {
    new MessageHandler3 ()
};
// Create a message handler chain with an end-point.
// Create a message handler chain with an endpoint
var routeHandlers = HttpClientFactory.CreatePipeline (
    new HttpControllerDispatcher (config), handlers);
config.Routes.MapHttpRoute (
    name: "Route2",
    routeTemplate: "api2 / {controller} / {id}",
    defaults: new {id = RouteParameter.Optional},
    constraints: null,
    handler: routeHandlers
);
If you feel something after reading this article, please give a recommendation

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.