我正在使用this教程創建Web API。我在Postman
中運行此API。 GET,PUT和DELETE方法正在工作完美,但是當我嘗試使用POST方法時,它不起作用,並給我一個例外。發現多個操作符合請求Web API asp.net
{ "Message": "An error has occurred.", "ExceptionMessage": "Multiple actions were found that match the request: \r\nPostProduct on type ProductStoreApi.Controllers.ProductController\r\nPostProducts on type ProductStoreApi.Controllers.ProductController", "ExceptionType": "System.InvalidOperationException", "StackTrace": " at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()" }
更新1
POST方法
public Product PostProduct(Product item)
{
item = repository.Add(item);
return item;
}
public HttpResponseMessage PostProducts(Product item)
{
item = repository.Add(item);
var response = Request.CreateResponse(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
注: -在教程中上述兩種方法都有相同的名稱,即PostProduct
。但是,當我嘗試寫出相同的名字時,我總是得到一個錯誤。
路線
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我已經搜索了很多文章,但無法找到完美的解決方案。
任何幫助將不勝感激。
我們可以看到你的控制器代碼嗎? –
@MatJ更新了問題 – faisal1208
教程中只有一個'PostProduct' - 第二個只是對第一個的更新。 –