Web API运行良好但我不明白为什么我得到“在控制器上找不到与请求错误相匹配的操作”异常错误,如果我将参数从“long parmAccountId”更改为“long?parmAccountId” “? (请参阅long数据类型旁边的“?”)。
有没有办法让它发挥作用?感谢..
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "MemberApi",
routeTemplate: "WebApi/Member/{controller}/{action}/{AccountId}/{UserId}",
defaults: new { AccountId = RouteParameter.Optional, UserId = RouteParameter.Optional }
);
}
}
public class DigitalLoanJacketController : ApiController
{
[ActionName("Upload")]
[HttpPost]
public string Post(long? parmAccountId, long? parmUserId, Foo parmFoo)
{
}
}
//JQUery...
var jsonRequest = { "Id": 3, "Name": "Scott Fletcher"};
$.ajax({
type: "POST",
async: false, /*false, //This need to be synchronous to the client can wait for a webserver response...*/
url: "https://localhost:44301/WebApi/Member/DigitalLoanJacket/Upload/e/83",
data: JSON.stringify(jsonRequest),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (parmData, parmTextStatus, parmXmlHttpRequest) {
alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);
},
error: function (parmXmlHttpRequest, parmTextStatus, parmErrorThrown) {
alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);
}
});
答案 0 :(得分:1)
根据评论更新:
尝试将您的行动声明更改为:
public class DigitalLoanJacketController : ApiController
{
[ActionName("Upload")]
[HttpPost]
public string Post(Foo parmFoo, long? parmAccountId = 0, long? parmUserId = 0)
{
}
}
或
public class DigitalLoanJacketController : ApiController
{
[ActionName("Upload")]
[HttpPost]
public string Post(Foo parmFoo, long? parmAccountId = null, long? parmUserId = null)
{
}
}
答案 1 :(得分:1)
Post methd的基本问题是,parmAccountId和parmUserId永远不会从url获取值。因为路径模板中的accountId,UserId与post方法中的parmAUountId,parmUserId不同。因此,模型绑定在这里会失败,因为它通过匹配名称来填充参数。
在Post方法中更改参数名称。它会起作用。
Public string Post(long? accountId, long? userId, Foo parmFoo)
{
}
模型绑定通过匹配名称填充方法参数。
这是Web Api中的请求流程。
此处模型绑定从路径参数填充方法中的前两个参数(accountid,userId),并从请求体填充最后一个参数(Foo)。模型绑定无法填充前两个参数,因为名称不匹配。