Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.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# 带多参数的Json post到WebApi vs MVC_C#_Json_Asp.net Mvc_Asp.net Web Api - Fatal编程技术网

C# 带多参数的Json post到WebApi vs MVC

C# 带多参数的Json post到WebApi vs MVC,c#,json,asp.net-mvc,asp.net-web-api,C#,Json,Asp.net Mvc,Asp.net Web Api,我们正在从MVC转向WepApi,以服务于我们的数据。这是我们如何更换控制器的示例 MVC: MVC控制器工作正常;然而,对于webapi,我们得到了以下信息: {"Message":"No HTTP resource was found that matches the request URI.","MessageDetail":"No action was found on the controller 'OfficeApiController ' that matches the requ

我们正在从MVC转向WepApi,以服务于我们的数据。这是我们如何更换控制器的示例

MVC:

MVC控制器工作正常;然而,对于webapi,我们得到了以下信息:

{"Message":"No HTTP resource was found that matches the request URI.","MessageDetail":"No action was found on the controller 'OfficeApiController ' that matches the request."}
如果我们的帖子只有一个参数,那么使用WebApi一切都正常

如果我们将徽章和薪水放在一个类中,并将post参数更改为该类,那么一切都正常工作

如果我们将它们作为两个参数提交,但以网络表单的形式提交,那么一切正常

只有当我们提交Json并且控制器有两个参数而不是一个将这些参数作为属性的类时,webapi才会失败

我们知道WebApi是用于Rest的,它应该获取/pot/delete/update一个资源,但我不明白为什么它不能解析两个Json参数

请注意,这不是我们的实际代码,也是提问的简化版本。可能有一些输入错误,但在我们的测试中,一切都符合并运行良好


谢谢你的帮助

WebAPI仅支持通过POST发送的一个参数。这没关系,因为您可以将所有内容包装到对象中

在jQuery
$.ajax
帖子中,实际上已经发送了一个参数

var data = JSON.stringify({ badge: '123', salary: '100000' });
这将创建一个具有两个属性的对象,
badge
salary

您需要将WebAPI代码更改为

[HttpPost]
public IEnumerable<Employee> SetSalary([FromBody]SalaryData data)
{
    // do stuff
}

现成的Web API不支持POST正文中的多个参数。典型的解决方案是将其封装到单个类中。可以用另一种方式完成,但是,好的,您需要覆盖默认的HttpParameterBinding。您可以尝试在webapi的url中发送参数吗?ActionApi/OfficeApi/SetSalary/{badge}/{salary}
{"Message":"No HTTP resource was found that matches the request URI.","MessageDetail":"No action was found on the controller 'OfficeApiController ' that matches the request."}
var data = JSON.stringify({ badge: '123', salary: '100000' });
[HttpPost]
public IEnumerable<Employee> SetSalary([FromBody]SalaryData data)
{
    // do stuff
}
public class SalaryData
{
    public string Badge {set; get;}
    public string Salary {set; get;}
}