简体   繁体   中英

HttpContext.Current.Request is always null in Custom Message Handler in ASP.NET Web Api

I have create a custom message handler in ASP.NET web Api like below

 public class CustomMessageHandler:DelegatingHandler
    {
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            return base.SendAsync(request, cancellationToken).ContinueWith(task =>
            {

                HttpRequest httpRequest = HttpContext.Current.Request;
                AuthenticationMode getAuthenticationMode = Application.GetAuthenticationMode();
                var authenticationFactory = new AuthenticationFactory();
                ICustomAuthentication authentication = authenticationFactory.CurrentAuthentication(getAuthenticationMode);
                authentication.ValidateRequest(httpRequest);
                HttpResponseMessage response = task.Result;
                response.StatusCode = HttpContext.Current.Response.StatusCode == 200 ? HttpStatusCode.OK : HttpStatusCode.Unauthorized;
                return response;
            });

        }
    }

inside this method i try to take HttpRequest but it always null.is anything i am missing? or is there any way to convert HttpRequestMessage to HttpRequest?

You can't rely on HttpContext being available. You need to look into alternate ways to do authentication that don't use HttpContext in Web API. If you are using Web API 2.0 you should look into Microsoft's OwinAuthenticationMiddleware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM