我有以下代码:
var keys = [];
keys.push({"classKey":"Dashboard","resourceKey":"Today's turnover"});
keys.push({"classKey":"Dashboard","resourceKey":"Get an overview directly from your receipts on location."});
$.ajax({
type: "POST",
url: "/Api/TranslationsApi/GetTranslationsByClassKey",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ translations: keys }),
success: function (result) {
alert(result.Data);
}
});
这个WebAPI控制器:
public class TranslationsApiController : ApiController
{
[System.Web.Http.HttpPost]
public JsonResult GetTranslationsByClassKey([FromBody]List<TranslationRequestModel> translations)
{
return new JsonResult { Data = translations.Count };
}
}
TranslationRequestModel:
public class TranslationRequestModel
{
public string ClassKey { get; set; }
public string ResourceKey { get; set; }
}
请求有效负载如下所示:
然而,我得到了一个
translate.js:40 POST http://localhost/Api/TranslationsApi/GetTranslationsByClassKey 404 (未找到)
我错过了什么?
答案 0 :(得分:0)
在WebApi(休息)调用中,您不必像调用Old WebServices一样调用该方法。您只使用Controller名称而不使用Controller这样的词:
/Api/TranslationsApi
在Rest中,为了拥有多个POST或GET方法,您需要为每个方法提供唯一的URL:
/Api/TranslationsApi/{param1}/{param2}
在WebApi2中,您可以使用RouteAttribute
执行此操作,如:
[Route("api/TranslationsApi/{param1}"), HttpPost]
public string PostMe2(int param1)
return "another POST value";
}
答案 1 :(得分:0)
如果使用默认路由模板设置路由,则应发布到/Api/TranslationsApi/
:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
如果您希望控制器操作绑定到列表,您还应该只发布数组。所以js应该是这样的:
$.ajax({
type: "POST",
url: "/Api/TranslationsApi/",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(keys),
success: function (result) {
alert(result.Data);
}
});