zoukankan      html  css  js  c++  java
  • HTTP Message Handlers in ASP.NET Web API

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

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

     

    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:

    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:

    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:

     

     

  • 相关阅读:
    nginx 禁止访问某个目录
    ssh 无法链接的解决思路
    linux 时间修改(同步到时间服务器)
    BitNami Gitlab的重启问题
    gitlab push时报错
    VirtualBox 安装centos后无法上网
    VirtualBox 创建64位系统的问题
    NOIP2010 题解
    NOIP2011 题解
    NOIP2012 题解
  • 原文地址:https://www.cnblogs.com/chucklu/p/10289181.html
Copyright © 2011-2022 走看看