ASP.NET Web Api中的自定义消息处理程序中的HttpContext.Current.Request始终为null

时间:2013-12-10 16:37:29

标签: .net asp.net-web-api

我在ASP.NET web Api中创建了一个自定义消息处理程序,如下所示

 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;
            });

        }
    }

在这个方法中,我尝试采用 HttpRequest ,但它总是为null。我错过了什么?或者有没有办法将HttpRequestMessage转换为HttpRequest?

1 个答案:

答案 0 :(得分:0)

您不能依赖HttpContext可用。您需要研究在Web API中不使用HttpContext进行身份验证的其他方法。如果您使用的是Web API 2.0,则应查看Microsoft的OwinAuthenticationMiddleware。