Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在ASP.NETMVC控制器中,如何获得一种方法来识别JSON中的数据并形成URLCoded格式?_C#_Json_Asp.net Mvc_Post - Fatal编程技术网

C# 在ASP.NETMVC控制器中,如何获得一种方法来识别JSON中的数据并形成URLCoded格式?

C# 在ASP.NETMVC控制器中,如何获得一种方法来识别JSON中的数据并形成URLCoded格式?,c#,json,asp.net-mvc,post,C#,Json,Asp.net Mvc,Post,我尝试使用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

我尝试使用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
    }
}
上述方法适用于表单URL编码参数,但不适用于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;
    }
}

我很好奇当
FromBodyAttribute
丢失时发生了什么,是您得到的错误:
参数字典包含参数的空条目
?@Tetsuyayayamamoto,我没有得到错误,但是UserRecord类的所有字段都是空的。发送json字符串时