asp.net-mvc - 如何绕过在 ASP.NET Web API 中发现多个操作的异常

标签 asp.net-mvc rest asp.net-mvc-routing asp.net-mvc-4 asp.net-web-api

在尝试为以下问题寻找解决方案时:

MVC Web Api Route with default action not working

大多数情况下,我遇到了“发现多个操作”的问题。如果路由机制发现一个路由匹配的 Action 不止一个,就会抛出异常 500。

例如,ValuesController 中有两个 Action :

[HttpGet]
public IEnumerable<String> Active()
{
    var result = new List<string> { "active1", "active2" };
    return result;
}

public IEnumerable<string> Get()
{
    return new[] { "value1", "value2" };
}

与默认路由匹配:
 routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{id}",
          defaults: new { id = RouteParameter.Optional }
      );


GET: /api/values 

将得到错误发现多个操作。

我的问题:如何通过选择指定的操作(选择第一个匹配的操作也可以)来绕过“发现多个操作”的异常。

更新 1:更新来自 tugberk 的评论,感谢指出。

更新 2:从 Mike 的评论更新,似乎问题不太正确,所以我改变了提问方式,不提及路由约束。

谢谢

最佳答案

首先,除非您在其上应用 HttpGet 属性,否则这些路由不可能匹配 Active 操作。我会假设你已经这样做了。第二件事是你想要的不合逻辑。您想发出一个 get 请求并有两个相同的操作。您现在正在使用所谓的基于 HTTP 方法的路由。对于您的情况,我确信所谓的基于 Action 的路由是最好的。

假设您有以下两个操作:

[HttpGet]
public IEnumerable<String> Active()
{
    var result = new List<string> { "active1", "active2" };
    return result;
}

[HttpGet]
public IEnumerable<string> Retrieve()
{
    return new[] { "value1", "value2" };
}

您的路线应如下所示:
routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

然后你可以向那些具有以下 URI 的人请求:

GET /controllername/retrieve

GET /controllername/active

关于asp.net-mvc - 如何绕过在 ASP.NET Web API 中发现多个操作的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11739288/

相关文章:

rest - 就增加的开销而言,分层RESTful url还是比纯url更受青睐?

带有 JAX-RS tomcat 服务器的 REST 返回 "requested resource is not available"

asp.net-mvc - asp mvc : specifying a view name does not change the url

C# ASP .Net MVC 4 可变长度路由映射

javascript - 在服务器端调用 MVC 中使用 javascript 变量

asp.net-mvc - Layout.cshtml 中的 ASP.NET MVC 搜索框

css - 无法在 MVC3 应用程序中切换到我样式化的 anchor 标记

json - 尝试在 Monotouch 上使用 ServiceStack 序列化自定义对象时出现 AOT 编译错误

asp.net-mvc - 使用查询字符串将 ASP.NET MVC URL 路由到 url

c# - 如何配置 Visual Studio 2017 以在 ASP.Net MVC https 站点中公开非加密端口