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

后端 未结 4 1527
暗喜
暗喜 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:55

    Accordingly to this "Best way to log/read request body in a middleware" thread, the following should work:

    // using Microsoft.AspNetCore.Http.Internal;
    
    public class SampleActionFilterAttribute : TypeFilterAttribute
    {
        ... 
    
        public void OnActionExecuting(ActionExecutedContext context)
        {
            // read body before MVC action execution
            string bodyData = ReadBodyAsString(context.HttpContext.Request);
        }
    
        private string ReadBodyAsString(HttpRequest request)
        {
            var initialBody = request.Body; // Workaround
    
            try
            {
                request.EnableRewind();
    
                using (StreamReader reader = new StreamReader(request.Body))
                {
                    string text = reader.ReadToEnd();
                    return text;
                }
            }
            finally
            {
                // Workaround so MVC action will be able to read body as well
                request.Body = initialBody; 
            }
    
            return string.Empty;
        }
     }
    

    Also similar approach described in Read request body twice SO post


    Update: above approach in ReadBodyAsString with will work if used in middleware, not in action filter. The difference is that when action filter is calling (even for OnActionExecuting), the body stream already has been read and [FromBody] model has been populated.

    The good nesw is that so it is possible to get model directly in action filter by using context.ActionArguments[""]. In your case:

    public void OnActionExecuted(ActionExecutedContext context)
    {
       var model = context.ActionArguments["model"] as NoteModel;
    }
    

提交回复
热议问题