[英]C# Web API route POST always returns 404
我有一個關於使用ASP.NET Web API 2路由POST請求的問題。
我似乎無法調用POST函數,它始終返回找不到的404。
{
"Message": "No HTTP resource was found that matches the request URI 'https://....../api/CombinedPOResponse/PostCombinedPOResponse'.",
"MessageDetail": "No action was found on the controller 'CombinedPOResponse' that matches the request."
}
有人可以指出我的配置損壞了嗎? 這是控制器的相關部分
namespace FormSupportService.Controllers
{
public class CombinedPOResponseController : ApiController
{
[HttpPost]
public IHttpActionResult PostCombinedPOResponse(string inputXml)
{
AddPurchaseOrderResponse response = new AddPurchaseOrderResponse();
//...
return Ok(response);
}
//...
}
}
然后提取WebApiConfig.cs
// UnitCodeLookup
config.Routes.MapHttpRoute(
name: "CombinedPOResponseApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { inputXml = RouteParameter.Optional }
);
我可以毫無問題地聯系到所有其他控制器,但是這很棘手。
謝謝
編輯:
我正在使用javascript調用服務:
$.ajax("/api/CombinedPOResponse/PostCombinedPOResponse",
{
accepts: "text/html",
data: {inputXml: inputXml},
dataType: 'json',
method: 'POST',
error: error,
success: success
});
首先,在以下代碼中
config.Routes.MapHttpRoute(
name: "CombinedPOResponseApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { inputXml = RouteParameter.Optional } //this line is not necessary
);
inputXml
設置inputXml
默認值,您可以忽略此設置。
要使請求[FromBody]
您必須將[FromBody]
添加到操作參數
[HttpPost]
public IHttpActionResult PostCombinedPOResponse([FromBody] string inputXml)
{
AddPurchaseOrderResponse response = new AddPurchaseOrderResponse();
//...
return Ok(response);
}
如果您嘗試使用此代碼,那么所有內容都可以正常工作,但inputXml
始終為null
。 要解決此問題,您需要更新JavaScript
$.ajax("/api/CombinedPOResponse/PostCombinedPOResponse",
{
accepts: "text/html",
data: {"": inputXml}, //empty name
dataType: 'json',
method: 'POST',
error: error,
success: success
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.