首页 > 编程语言 >HTTP Message Handlers in ASP.NET Web API

HTTP Message Handlers in ASP.NET Web API

时间:2024-07-05 11:44:13浏览次数:22  
标签:Web ASP HTTP request SendAsync handler message response

HTTP Message Handlers in ASP.NET Web API

In this article

  1. Server-Side Message Handlers
  2. Custom Message Handlers
  3. Adding a Handler to the Pipeline
  4. Example: X-HTTP-Method-Override

message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

Typically, a series of message handlers are chained together. The first handler receives 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 called a delegating handler.

Diagram of message handlers chained together, illustrating process to receive an H T T P request and return an H T T P response.

Server-Side Message Handlers

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

  • HttpServer gets the request from the host.
  • HttpRoutingDispatcher dispatches the request based on the route.
  • HttpControllerDispatcher sends the request to a Web API controller.

You can add custom 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:

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

This diagram shows two custom handlers inserted into the pipeline:

Diagram of server-side message handlers, displaying two custom handlers inserted into the Web A P I pipeline.

 Note

On the client side, HttpClient also uses message handlers. For more information, see HttpClient Message Handlers.

Custom Message Handlers

To write a custom message handler, derive from System.Net.Http.DelegatingHandler and override the SendAsync method. This method has the following signature:

C#
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:

  1. Process the request message.
  2. Call base.SendAsync to send the request to the inner handler.
  3. The inner handler returns a response message. (This step is asynchronous.)
  4. Process the response and return it to the caller.

Here is a trivial example:

C#
public class MessageHandler1 : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Debug.WriteLine("Process request");
        // Call the inner handler.
        var response = await base.SendAsync(request, cancellationToken);
        Debug.WriteLine("Process response");
        return response;
    }
}
 

 Note

The call to base.SendAsync is asynchronous. If the handler does any work after this call, use the await keyword, as shown.

A delegating handler can also skip the inner handler and directly create the response:

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

        // Note: TaskCompletionSource creates a task that does not contain a delegate.
        var tsc = new TaskCompletionSource<HttpResponseMessage>();
        tsc.SetResult(response);   // Also sets the task state to "RanToCompletion"
        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).

Diagram of custom message handlers, illustrating process to create the response without calling base dot Send Async.

Adding a Handler 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:

C#
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.

Notice that you don't need to set the inner handlers; the Web API framework automatically connects the message handlers.

If you are self-hosting, create an instance of the HttpSelfHostConfiguration class and add the handlers to the MessageHandlers collection.

C#
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.

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:

Console
X-HTTP-Method-Override: PUT
 

Here is a message handler that adds support for X-HTTP-Method-Override:

C#
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.
        if (request.Method == HttpMethod.Post && request.Headers.Contains(_header))
        {
            // Check if the header value is in our methods list.
            var method = request.Headers.GetValues(_header).FirstOrDefault();
            if (_methods.Contains(method, StringComparer.InvariantCultureIgnoreCase))
            {
                // Change 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.

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

Example: Adding a Custom Response Header

Here is a message handler that adds a custom header to every response message:

C#
// .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.

This example uses the await keyword to perform work asynchronously after SendAsync completes. If you are targeting .NET Framework 4.0, use the Task<T>.ContinueWith method:

C#
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

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:

C#
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.

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.

 Note

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.

Per-Route Message Handlers

Handlers in the HttpConfiguration.MessageHandlers collection apply globally.

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

C#
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:

Diagram of per route message handlers pipeline, illustrating process to add a message handler to a specific route by defining the route.

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.

Alternatively, a per-route message handler can delegate to HttpControllerDispatcher, which then dispatches to a controller.

Diagram of per route message handlers pipeline, showing process to delegate to h t t p Controller Dispatcher, which then dispatches to a controller.

The following code shows how to configure this route:

C#
// List of delegating handlers.
DelegatingHandler[] handlers = new DelegatingHandler[] {
    new MessageHandler3()
};

// Create a message handler chain with an end-point.
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
);
       

标签:Web,ASP,HTTP,request,SendAsync,handler,message,response
From: https://www.cnblogs.com/sexintercourse/p/18285503

相关文章

  • nginx+tomcat+二级域名+https
    1.添加域名解析在腾讯云或者阿里云中添加域名解析,解析到具体得ip​​2.购买SSL证书在腾讯云或者阿里云中购买相应的SSL,基本上每个SSL只能解析一个HTTPS,所以如果你有多个二级域名设置HTTPS的话,需要申请多个SSL3.安装多个tomcat3.1下载tomcat安装包放入服务器中从网上下载t......
  • JavaWeb—jsp篇
    概述JavaServerPages:java服务器端页面      可以理解为:一个特殊的页面,其中既可以指定定义html标签,又可以定义java代码      用于简化书写 原理jsp实际就是一个servletjsp就是java代码  脚本<% 代码%>:定义的java代码,在service方法中。......
  • 政务服务网用哪种HTTPS证书
    政务服务网作为连接政府与民众的重要桥梁,承载着提供高效、安全、透明的在线服务的重任。在众多HTTPS证书类型中,政务服务网应当如何选择最合适的证书?一、证书类型推荐OV(组织验证)SSL证书:特点:OVSSL证书需要验证申请证书组织的真实身份,包括组织名称、地址、电话号码等信息。......
  • China.NETConf2019 - 用ASP.NETCore构建可检测的高可用服务
    一、前言2019中国.NET开发者峰会(.NETConfChina2019)于2019年11月10日完美谢幕,校宝在线作为星牌赞助给予了峰会大力支持,我和项斌等一行十位同事以讲师、志愿者的身份公司参与到峰会的支持工作中,我自己很荣幸能够作为讲师与大家交流,分享了主题《用ASP.NETCore构建可检测的高......
  • 关于nginx HTTP安全响应问题
    目录一、背景二、http基本安全配置2.1host头攻击漏洞2.2httpmethod请求方式攻击漏洞2.3点劫持漏洞(X-Frame-Options)2.4X-Download-Options响应头缺失2.5Content-Security-Policy响应头缺失2.6Strict-Transport-Security响应头缺失2.7X-Permitted-Cross-Domain-Po......
  • springboot 中推荐使用哪些比较好的 web 客户端 SDK
    在SpringBoot中,有几种常用和推荐的Web客户端SDK,可以用于与RESTful或其他类型的Web服务进行交互。1.SpringWebClientSpringWebClient是Spring5中引入的非阻塞、响应式的Web客户端,推荐用于现代SpringBoot应用。特点响应式编程:支持响应式编程模型,适用于需......
  • 05 Web APIs
    一DOM-获取元素DOM是操作页面文档,开发网页特效和实现用户交互。document是DOM顶级对象document.write()1.1获取DOM元素CSS选择器来获取DOM元素选择匹配的第一个元素:document.querySelector('css选择器')console.dir(对象):用来输出对象格式数据选择匹配的多个元素对象:do......
  • Asp .Net Core 系列:基于 Castle DynamicProxy + Autofac 实践 AOP 以及实现事务、用户
    目录什么是AOP?.NetCore中有哪些AOP框架?基于CastleDynamicProxy实现AOPIOC中使用CastleDynamicProxy实现事务管理实现用户自动填充什么是AOP?AOP(Aspect-OrientedProgramming,面向切面编程)是一种编程范式,旨在通过将横切关注点(cross-cuttingconcerns)从主要业务逻辑......
  • WEB03Maven&Mybatis
    maven基础Maven是apache提供的一个项目管理工具,它的作用就是管理项目介绍依赖管理依赖管理主要指的是项目怎样引入依赖包,maven会将所有需要的依赖包放在本地仓库中,然后每个项目通过配置文件引入自己所需要的那部分jar包在maven本地仓库中是按照什么结构存放的?我......
  • C#面:ASP.NET Core ⽐ ASP.NET 更具优势的地⽅是什么?
    ASP.NETCore相对于ASP.NET具有以下几个优势:跨平台支持:ASP.NETCore是跨平台的,可以在Windows、Linux和macOS等多个操作系统上运行。这使得开发人员可以选择更适合他们的操作系统来进行开发和部署。更轻量级:ASP.NETCore是一个轻量级的框架,它具有更小的内存占用和更快的启动......