问题描述:

I am trying to get the body of a POST Request in an ActionFilterAttribute. The bodyString is returned empty without getting any exceptions. I am testing this with a simple { "name": "value" } JSON.

public override void OnActionExecuted(ActionExecutedContext context)

{

string bodyString = string.Empty;

using (System.IO.MemoryStream m = new System.IO.MemoryStream())

{

try

{

if (context.HttpContext.Request.Body.CanSeek == true)

context.HttpContext.Request.Body.Position = 0;

context.HttpContext.Request.Body.CopyTo(m);

bodyString = Encoding.UTF8.GetString(m.ToArray());

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

}

}

base.OnActionExecuted(context);

}

网友答案:

The reason why the MemoryStream cannot read the data because it has already been read by [FromBody] from my method:

[HttpPost]
[ServiceFilter(typeof(ETagFilter))]
public IActionResult Post([FromBody]JToken body) 
{ 
    //Do something with the data
}

To access the body in the ActionFilter I used:

var bodyString = context.ActionArguments["body"];
相关阅读:
Top