WebApi在filter内获取后期原始主体

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

LogFilter.cs

public override void OnActionExecuting(HttpActionContext filterContext) { try { Task 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); } 

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

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