Is there any way to get request body in .NET Core FilterAttribute?

后端 未结 4 1522
暗喜
暗喜 2021-02-08 23:26

Sample of my request

http://localhost:8065/api/note
POST
content-type:application/json
request body: { \"id\" : \"1234\", \"title\" : \"test\", \"status\" : \"dr         


        
4条回答
  •  日久生厌
    2021-02-08 23:40

    If you're using IActionResult in your controllers and you want the .NET objects, you can write a filter like this:

    public class SampleFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result is ObjectResult)
            {
                var objResult = (ObjectResult)context.Result;
            }
        }
    
        public void OnActionExecuting(ActionExecutingContext context)
        {
    
        }
    }
    

    By the point it hits OnActionExecuted, the ObjectResult task has already completed, so you can just extract the value. You can also get the StatusCode with objResult.StatusCode.

    In the controller, return Ok(...) actually creates an OkObjectResult, etc.

    If you specifically want the serialzied result, then Set's answer is more valid.

提交回复
热议问题