添加 MessageHandler 后 HttpContext 为 null

HttpContext is null after adding MessageHandler

我正在开发 WebAPI 并且一直在接收我的 POST 数据,如下所示:

[HttpPost]
        public Int16 Foo()
        {
            var input = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
            Model_Deserialized model = JsonConvert.DeserializeObject<Model_Deserialized>(input);
            ...
        }

最近我觉得有必要记录所有发送过来的请求。我正在尝试使用 http://weblogs.asp.net/fredriknormen/log-message-request-and-response-in-asp-net-webapi 中建议的方法,但在执行这些步骤后,我的输入变量开始变成空字符串。

这就是我的消息处理程序的样子

public abstract class MessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
            var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri);

            var requestMessage = await request.Content.ReadAsByteArrayAsync();

            String ip;

            if (request.Properties.ContainsKey("MS_HttpContext"))
            {
                var ctx = request.Properties["MS_HttpContext"] as HttpContextWrapper;
                if (ctx != null)
                {
                    ip = ctx.Request.UserHostAddress;
                }
            }

            else
            {
                 ip = "error";
            }

            await IncommingMessageAsync(corrId, requestInfo, requestMessage, ip);

            var response = await base.SendAsync(request, cancellationToken);

            return response;
        }


        protected abstract Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message, String ip);
    }

这是我的 MessageLoggingHandler

public class MessageLoggingHandler : MessageHandler
    {
        protected override async Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message, String ip)
        {
            await Task.Run(() =>
                WriteToFile(ip + "{" + correlationId + "} - Request: {" + requestInfo + "}\r\n{" + Encoding.UTF8.GetString(message) + "}"));
        }


        private void WriteToFile(string text)
        {
            string path = "C:\Logs\ServiceLog" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + ".txt";
            using (StreamWriter writer = new StreamWriter(path, true))
            {
                writer.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + "--" + text);
                writer.Close();
            }
        }
    }

我也把这个添加到我的 Global.asax

GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageLoggingHandler());

在我的 web.config 中,我已经尝试添加

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<compilation debug="true" targetFramework="4.5">

有没有办法坚持这个方法而不是创建一个记录例程并从每个函数调用它?

明确一点 HttpContext 不能为空 - 它是静态的。那么 HttpContext.Current 是空的吗?或者我的猜测是 HttpContext.Current.Request.InputStream 为空。 Web api 自动读取流并处理它并将 post 主体反序列化为您的操作输入。因此,您应该将 Web Api 操作编码为如下内容:

[HttpPost]
public Int16 Foo(Model_Deserialized model)
{

    ...
}