WebApi在过滤器中获取后期原始主体

时间:2015-09-01 19:16:56

标签: c# asp.net-mvc asp.net-web-api

我正在创建一个日志,我需要检索请求体以保存在db中。我用HttpActionContext创建了一个过滤器。 我尝试通过filterContext.Request.Content.ReadAsStringAsync()恢复。 但它总是给我一个空字符串。

LogFilter.cs

public override void OnActionExecuting(HttpActionContext filterContext)
    {
        try
        {
            Task<string> content = filterContext.Request.Content.ReadAsStringAsync();
            string body = content.Result;

            logModel.RequestLog rl = new logModel.RequestLog();
            rl.IP = ((HttpContextWrapper)filterContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            rl.Type = filterContext.ControllerContext.RouteData.Values["controller"].ToString().ToUpper();
            rl.URL = filterContext.Request.RequestUri.OriginalString;
            rl.Operation = filterContext.Request.Method.Method;
            rl.RequestDate = DateTime.Now;


            filterContext.ControllerContext.RouteData.Values.Add("reqID", new deviceLog.RequestLog().Add(rl).ID.ToString());
        }
        catch { }
        //return new deviceLog.RequestLog().Add(rl);
        base.OnActionExecuting(filterContext);
    }

1 个答案:

答案 0 :(得分:15)

也许请求流已经到达结束。尝试将流重置位置重置为开头:

public class MyAttribute:ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionContext actionContext)
    {
        string rawRequest;
        using (var stream = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))
        {
            stream.BaseStream.Position = 0;
            rawRequest = stream.ReadToEnd();
        }
    }
}