How to implement HttpMessageHandler in Web API?

后端 未结 2 1018
长情又很酷
长情又很酷 2020-12-16 13:03

In an ASP.NET 4.5 MVC 4 Web API project, I want to add a custom HttpMessageHandler. I\'ve changed WebApiConfig class (in \\App_Satrt\\WebApiConfig.

2条回答
  •  失恋的感觉
    2020-12-16 13:32

    To write a custom message handler, you should derive from System.Net.Http.DelegatingHandler

    class CustomMessageHandler : DelegatingHandler
    {
        protected override Task 
          SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IPrincipal principal = new GenericPrincipal(
                new GenericIdentity("myuser"), new string[] { "myrole" });
            Thread.CurrentPrincipal = principal;
            HttpContext.Current.User = principal;
    
            return base.SendAsync(request, cancellationToken);
        }
    }
    

    And call base.SendAsync to send the request to the inner handler.

提交回复
热议问题