我正在使用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' - 第二个只是对第一个的更新。 –