Asp.Net Web API 2 Lesson 4: HttpClient Message Processor

Keywords: ASP.NET Java JSP network

Share: I have several Aliyun coupons, which can offer up to 50% discount for purchasing or upgrading Aliyun's corresponding products. Ticket address: https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03

Asp.Net Web API Navigation

Asp.Net Web API Lesson 1: Introduction http://www.cnblogs.com/aehyok/p/3432158.html

Asp.Net Web API Lesson 2: CRUD Operations http://www.cnblogs.com/aehyok/p/3434578.html

Asp.Net Web API Lesson 3:.NET Client Calls Wep API http://www.cnblogs.com/aehyok/p/3439698.html

Preface

Message processor is a class that receives HTTP requests and returns HTTP responses.

Typically, a series of message processing is linked together. The first processor receives the HTTP request, does some processing, and then passes the request to the next processor. At some point, the response is created and traced back. This pattern is called a delegate processor.

On the client side, the HTTPClient class uses a message processor to process requests. The default processor is HTTP ClientHandler, which sends requests over the network and receives responses from the server. You can insert a custom message processor into the client pipeline.

Asp.Net Web API can also use message processors on the server side. For more information, refer to "HTTP Message Processor" (not yet implemented).

Custom Message Processor

To write a message processor, you need to derive from System.Net.Http.Delegating Handler and rewrite the SendAsync method. The following is the signature of the method:

System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);

This method takes the HttpRequestMessage parameter as input and asynchronously returns an HttpResponseMessage. A typical implementation is as follows:

1. Processing request messages.

2. Call base.SendAsync to send the request to the internal processor.

3. The internal processor returns a response message. (This step is asynchronous)

4. Processing the response and returning it to the caller.

The following example shows a message processor that adds a custom header to an external request.

    public class MessageHandler : DelegatingHandler
    {
        private int _count = 0;
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            _count++;
            request.Headers.Add("X-Custom-Header", _count.ToString());
            return base.SendAsync(request, cancellationToken);
        }
    }

The call to base.SendAsync is asynchronous. If the processor has some work to do after the call, it needs to use the await keyword to continue executing after the method has been completed.

The following example shows a processor that logs error codes. How to log doesn't matter much, but this example shows how to get the response inside the processor.

    public class LoggingHandler : DelegatingHandler 
    { 
        StreamWriter _writer; 
        public LoggingHandler(Stream stream)
        { 
            _writer = new StreamWriter(stream);
        }

        protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
            if (!response.IsSuccessStatusCode) 
            { 
                _writer.WriteLine("{0}\t{1}\t{2}", request.RequestUri,(int)response.StatusCode, response.Headers.Date); 
            } 
            return response; 
        }
        protected override void Dispose(bool disposing) 
        { 
            if (disposing) 
            { 
                _writer.Dispose(); 
            } 
            base.Dispose(disposing); 
        } 
    }

Adding a message processor to the client pipeline

To add a custom processor to HttpClient, use the HttpClientFactory.Create method:

HttpClient client = HttpClientFactory.Create(new MessageHandler());

Message processors are invoked in the order in which they are passed to the Create method. So the processor is embedded, and the response message is sent in the opposite direction. That is, the last processor gets the response message first.

summary

This article focuses on HTTPClient message processor. The code involved has been shown in the text, and will not upload for the time being.

Reference link for this article http://www.asp.net/web-api/overview/web-api-clients/httpclient-message-handlers

 

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

Posted by CanMan2004 on Tue, 11 Dec 2018 12:03:06 -0800