2017-09-19 36 views
0

我正在使用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 } 
     ); 

我已经搜索了很多文章,但无法找到完美的解决方案。

任何帮助将不胜感激。

+1

我们可以看到你的控制器代码吗? –

+0

@MatJ更新了问题 – faisal1208

+4

教程中只有一个'PostProduct' - 第二个只是对第一个的更新。 –

回答

2

你误会本教程的PostProduct方法:

接下来,我们将添加一个方法到ProductsController类来创建一个 新产品。下面是一个简单的方法实现:

// Not the final implementation! 
public Product PostProduct(Product item) 
{ 
    item = repository.Add(item); 
    return item; 
} 

请注意,这里的代码明确地提醒你,这是不是这种方法的最终实现

在本教程的后面,我们有:

的ASP.NET Web API可以轻松操作HTTP响应消息。 这里是提高执行

public HttpResponseMessage PostProduct(Product item) 
{ 
    item = repository.Add(item); 
    var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item); 

    string uri = Url.Link("DefaultApi", new { id = item.Id }); 
    response.Headers.Location = new Uri(uri); 
    return response; 
} 

(我的重点)

你要更换早期PostProduct方法与此改进执行。

+0

是的,我想知道教程。 :) – faisal1208