Search code examples
c#asp.net-core.net-core

How to find the type of Httpcontext.Request.Body in .net core


How can I find the Type of the RequestBody object in Httpcontext in middleware and deserialize it to the original Type? e.g. this is the request body {"username":"zxc", "password":"123"} and I have

public class LoginRequest
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

Is that possible to convert the request body to an object of LoginRequest? (this is just an example and it can be different types so I don't know which type is coming to middleware)


Solution

  • It is not possible to do it inside IMiddleware, but it is going to be possible for example inside IActionFilter. This answer contains a good, short explanation of what is ASP.NET Core middleware and when it occurs: https://stackoverflow.com/a/61957091/2895299

    Inside IMiddleware, you have access to HttpContext but model binding hasn't occured yet. If you want to know the type of request body you need to be inside MVC pipeline, after binding.

    Following code snippet gets the type of request's argument:

        public class SampleFilter : IActionFilter
        {
            public void OnActionExecuted(ActionExecutedContext context)
            {
                //
            }
    
            public void OnActionExecuting(ActionExecutingContext context)
            {
                var arg = context.ActionArguments.First().Value;
                var argType = arg.GetType();
    
                //do whatever you want with type information 
            }
        }
    

    Obviously it is not bullet proof, it is just a dummy example but you should get the idea. Just please not that using reflection to get type of every request may have a significant performance impact on your application.

    If you are interested in how MVC Pipeline works you may also check https://livebook.manning.com/book/asp-net-core-in-action/chapter-13/