[英]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?如何在中间件的Httpcontext中找到RequestBody object的Type并将其反序列化为原始Type? eg this is the request body {"username":"zxc", "password":"123"}
and I have例如,这是请求正文{"username":"zxc", "password":"123"}
我有
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
?是否可以将请求正文转换为LoginRequest
的 object ? (this is just an example and it can be different types so I don't know which type is coming to middleware) (这只是一个例子,它可以是不同的类型,所以我不知道中间件是哪种类型)
It is not possible to do it inside IMiddleware
, but it is going to be possible for example inside IActionFilter
.在IMiddleware
内部是不可能的,但例如在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这个答案包含一个很好的简短解释,什么是 ASP.NET 核心中间件以及它发生的时间: https://stackoverflow.com/a/61957091/2895299
Inside IMiddleware
, you have access to HttpContext
but model binding hasn't occured yet.在IMiddleware
内部,您可以访问HttpContext
但 model 绑定尚未发生。 If you want to know the type of request body you need to be inside MVC pipeline, after binding.如果您想知道绑定后需要在 MVC 管道中的请求主体的类型。
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/如果您对 MVC 管道的工作原理感兴趣,您还可以查看https://livebook.manning.com/book/asp-net-core-in-action/chapter-13/
There are lots of ways to do this but I think you can use GetType() method and maybe you can achieve what you want.有很多方法可以做到这一点,但我认为你可以使用 GetType() 方法,也许你可以实现你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.