Multiple IHttpActionResults GET's within a single ApiController fail

假装没事ソ 提交于 2020-01-05 23:05:53

问题


I am playing with WebApi2 and came across an odd issue.

I have updated the default ValuesController to use IHttpActionResult

like

    public class ValuesController : ApiController
{
    // GET api/values
    [HttpGet]
    public IHttpActionResult Get()
    {
        return Ok(new string[] { "value1", "value2" });
    }

    // GET api/values/get2
    [HttpGet]
    public IHttpActionResult Get2()
    {
        return Ok(new string[] { "value1", "value2" });
    }

When I try call Get() within postman I get an error

{ "Message": "An error has occurred.", "ExceptionMessage": "Multiple actions were found that match the request: \r\nSystem.Web.Http.IHttpActionResult Get() on type WebApplication1.Controllers.ValuesController\r\nSystem.Web.Http.IHttpActionResult Get2() on type WebApplication1.Controllers.ValuesController", "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.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()" }

Do I need to manually create a route for each to get this to work?

Something so simple, yet causing me a headache!


回答1:


It's because you have two GET requests which take no parameters so WebApi has no way of differentiating between the two. One way would be to set up different routes for each method as you say. The easiest way to get around this though is to use the Attribute Routing library which allows you to define different routes at the Controller and Action levels really simply like this:

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{   
    [GET("Get")]
    public IHttpActionResult Get()
    {
        return Ok(new string[] { "value1", "value2" });
    }

    [GET("Get2")]
    public IHttpActionResult Get2()
    {
        return Ok(new string[] { "value1", "value2" });
    }
}


来源:https://stackoverflow.com/questions/21010449/multiple-ihttpactionresults-gets-within-a-single-apicontroller-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!