本文介绍了多IHttpActionResults得到一个ApiController中的失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我玩WebApi2并在一个奇怪的问题就来了。

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

我已经更新了默认Values​​Controller使用IHttpActionResult

I have updated the default ValuesController to use IHttpActionResult

    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" });
    }

当我尝试调用Get()邮递员内我得到一个错误

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

{
      消息:发生了错误。
      ExceptionMessage:多的行动中发现匹配的要求,即:在类型上WebApplication1型WebApplication1.Controllers.Values​​Controller \\ r \\ nSystem.Web.Http.IHttpActionResult Get2(个)\\ r \\ nSystem.Web.Http.IHttpActionResult的get() .Controllers.Values​​Controller
      ExceptionType:System.InvalidOperationException,
      堆栈跟踪:在System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\\ r \\ n在System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\\ r \\ n在System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext,的CancellationToken的CancellationToken)\\ r \\ n的系统。 Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HTT prequestMessage请求的CancellationToken的CancellationToken)\\ r \\ n在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!

推荐答案

这是因为你有没有参数所以的WebAPI没有两个之间的区别方式二送请求。一种方法是建立不同的路线为每个​​方法如你所说。要解决这个问题,虽然最简单的方法是使用库,可以让你在控制器定义不同的路线,行动水平真的只是这样的:

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" });
    }
}

这篇关于多IHttpActionResults得到一个ApiController中的失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 14:12