![](/img/trans.png)
[英]Controller action that receives any data in xml json or form-urlencoded
[英]In ASP.Net MVC controller, how do I get a method to recognize data from JSON and Form-urlEncoded formats?
我正在尝试使用ASP.NET代码MVC来处理HTTP POST请求,如下所示:
[Route("coreapi/control")]
public class Control : Controller
{
[HttpPost(userGroups/{groupId}/users/{userId})]
public int AddRecord(UserRecord record){
//This even populates the UserId and GroupId fields in record from the route
}
}
以上适用于Form-UrlEncoded参数,但不适用于JSON。
如果我想使用JSON,则需要使用[FromBody]属性,如下所示:
[Route("coreapi/control")]
public class Control : Controller
{
[HttpPost(userGroups/{groupId}/users/{userId})]
public int AddRecord([FromBody]UserRecord record, int groupId, int userId){
//this doesn't look in the route to populate info anymore
record.GroupId = groupId;
record.UserId = userId;
}
}
我如何使两者同时使用?
因此,这看起来确实很愚蠢,但是通过实验和阅读这篇内容丰富的文章 ,看来唯一的方法就是使用两种单独的方法。
一种用于形式编码的数据
[Route("coreapi/control")]
public class Control : Controller
{
[HttpPost(userGroups/{groupId}/users/{userId}/add)]
public int AddRecord(UserRecord record){
//This even populates the UserId and GroupId fields in record from the route
}
}
还有一个用于json:
[Route("coreapi/control")]
public class Control : Controller
{
[HttpPost(userGroups/{groupId}/users/{userId}/addJson)]
public int AddRecordJson([FromBody]UserRecord record, int groupId, int userId){
//this doesn't look in the route to populate info anymore
record.GroupId = groupId;
record.UserId = userId;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.