C# Web Api请求无效
我有一条路线:C# Web Api请求无效,c#,asp.net-mvc,asp.net-web-api,C#,Asp.net Mvc,Asp.net Web Api,我有一条路线: routes.MapRoute (name: "apicontroller2", url: "api/{controller}/{action}/", defaults: new { controller = "Default2", action = "Index" } ); 以及具有两种post方法的Default2Controller: [HttpPost] public
routes.MapRoute (name: "apicontroller2",
url: "api/{controller}/{action}/",
defaults: new { controller = "Default2", action = "Index" }
);
以及具有两种post方法的Default2Controller:
[HttpPost]
public HttpResponseMessage Post(ttReview review)
{
...
}
[HttpPost]
public HttpResponseMessage PostPro(ttbewertungenpro pro)
{
...
}
当我通过webserver/API/default2/postro/
或webserver/API/default2/Post/
ajaxpost调用这些API方法时,我得到了错误:
ExceptionMessage=Multiple actions were found that match the request:
System.Net.Http.HttpResponseMessage Post(WT.Models.ttReview) on type WT.Controllers.Default2Controller
System.Net.Http.HttpResponseMessage PostPro(WT.Models.ttbewertungenpro) on type WT.Controllers.Default2Controller
我的ajax调用是:
$.ajax({
url: "../api/default2/Post", // or "../api/default2/PostPro",
type: 'POST',
dataType: "text",
data: review, // or pro
success: function (test) {
},
error: function (test) {
alert("Error");
}
}
我的路线错了还是怎么了?
当我删除一个方法时,其他方法会起作用…签出属性计算(http://nuget.org/packages/AttributeRouting.WebApi)
绘制路线图要容易得多
范例
[POST("Page/Method")]
public HttpResponseMessage Post(ttReview review)
{
...
}
对于全新的空白WebAPI项目,我没有接触过global.asax文件 家庭控制器
[HttpPost]
public HttpResponseMessage Post(string review)
{
return new HttpResponseMessage(HttpStatusCode.Created);
}
[HttpPost]
public HttpResponseMessage PostPro(string pro)
{
return new HttpResponseMessage(HttpStatusCode.Created);
}
Index.cshtml
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script>
$(document).ready(function () {
$("#submit").click(function() {
$.ajax({
url: "home/Post", // or "../api/default2/PostPro",
type: 'POST',
dataType: "text",
data: "test", // or pro
success: function(test) {
},
error: function(test) {
alert("Error");
}
});
});
});
</script>
<input type="submit" value="submit" id="submit" />
$(文档).ready(函数(){
$(“#提交”)。单击(函数(){
$.ajax({
url:“home/Post”、//或“./api/default2/postro”,
键入:“POST”,
数据类型:“文本”,
数据:“测试”、//或pro
成功:功能(测试){
},
错误:函数(测试){
警报(“错误”);
}
});
});
});
这对我来说很好,所以问题一定是您的路径/路由。Posts for/Default2/将查找Default2Controller,但您的控制器名为DefaultController2。当您将
PostPro
重命名为Test
以除去公共前缀Post
时会发生什么?您确定需要。。在URL中的API前面?这解决了问题,但我仍然必须手动定义每个路由。这与其说是解决初始问题,不如说是一种变通方法。所以我还不想把它作为一个答案。