I' creating a log and i need to retrieve the request body to save in db. i created a filter with HttpActionContext. I tried recover via filterContext.Request.Content.ReadAsStringAsync().Result; but it always return me an empty string.
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);
}
Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules. For example, consider the following GET method.
Using [FromUri] To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.
The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter.
Maybe request stream already reached to end. Try reset stream position to beginning:
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With