[英]How do I read multiple parameters from a JSON request body in ASP.NET Core?
Essentially, I have an API endpoint like this:本质上,我有一个 API 端点,如下所示:
public async Task<ActionResult<UserDTO>> SignUp(string username, string password, Guid inviteId)
I want all these parameters to come from a JSON object in the request body like so:我希望所有这些参数都来自请求正文中的 JSON object ,如下所示:
{
'username': 'foo',
'password': 'bar',
'inviteId': '00000000-0000-0000-0000-000000000000'
}
I know I can create a class with these parameters as fields, but is there a cleaner way to do this?我知道我可以使用这些参数作为字段创建 class,但是有没有更简洁的方法来做到这一点? Also, how do I accept a parameter from the JSON object and another source?
另外,我如何接受来自 JSON object和其他来源的参数? (ie
inviteId
could come from the JSON object or the query string) (即,
inviteId
可能来自 JSON object 或查询字符串)
EDIT : To clarify, I don't want to use a custom class, or something like JObject.编辑:澄清一下,我不想使用自定义 class或JObject 之类的东西。 I want the function to receive its parameters directly, without having to do any manual unpacking or parsing.
我希望 function 直接接收其参数,而无需进行任何手动解包或解析。 Basically, the function signature should stay as
SignUp(string username, string password, Guid inviteId)
, and the solution should add on to ASP.NET's model binding functionality.基本上,function 签名应保留为
SignUp(string username, string password, Guid inviteId)
,并且该解决方案应添加到 ASP.NET 的 model 绑定功能。 Also, I don't want to use any third-party packages if I can help it.另外,如果我能提供帮助,我不想使用任何第三方软件包。
Use JObject
in NewtonSoft package
.在
NewtonSoft package
JObject
import进口
using Newtonsoft.Json.Linq;
Change the method like,改变方法,如
public async Task<ActionResult<UserDTO>> SignUp([FromBody] JObject dataObject)
you can access the data by key,您可以通过键访问数据,
var username = dataObject["username"].ToString(); var password= dataObject["password"].ToString();
Using this mechanism, you can process complex JSON objects without model binding.使用这种机制,您可以在没有 model 绑定的情况下处理复杂的 JSON 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.