【问题标题】:Route not recognised in MVC 4 WebAPI在 MVC 4 WebAPI 中无法识别路由
【发布时间】:2013-03-11 07:44:30
【问题描述】:

虽然我在直接 MVC 中使用了路由,但我并没有太多使用 ASP.NET WebAPI。显然我做错了什么,也许有人可以帮忙? 我有一个名为 UsersController 的控制器和两个方法,Register 和 Details,它们都接受两个字符串参数并返回一个字符串,都标记为 HttpGet。 最初我从 WebApiConfig.cs 中的两个路由映射开始:

config.Routes.MapHttpRoute(
      name: "TestApi",
      routeTemplate: "api/{controller}/{action}/{userId}/{key}"
  );
  config.Routes.MapHttpRoute(
      name: "Test2Api",
      routeTemplate: "api/{controller}/{action}/{userId}/{class}"
  );

通过此设置,只能找到 URL 的第一个路由,例如:

http://<domain>/api/users/register/a123/b456/

如果我打电话:

http://<domain>/api/users/details/a123/b456/

我得到一个 404。如果我交换两条路由,那么我可以调用 Details 方法但不能调用 Register 方法,再次得到 404。我的解决方法是更具体地处理路由:

config.Routes.MapHttpRoute(
      name: "TestApi",
      routeTemplate: "api/{controller}/register/{userId}/{key}"
  );
  config.Routes.MapHttpRoute(
      name: "Test2Api",
      routeTemplate: "api/{controller}/details/{userId}/{class}/"
  );

UsersController 看起来像:

namespace HelloWebAPI.Controllers
{
  using System;
  using System.Web.Http;
  using HelloWebAPI.Models;

    public class UsersController : ApiController
    {
      [HttpGet]
      public string Register(string userId, string key)
      {
        return userId + "-" + key;
      }

      [HttpGet]
      public string Enrolments(string userId, string @class)
      {
        return userId + "-" + @class
      }
    }
}

所以我不明白为什么第二个注册的路由的 {action} 组件没有与正确的方法关联。

谢谢

【问题讨论】:

  • 您能分享一下您的操作“注册”和“详细信息”是什么样的吗?
  • 我已将课程添加到帖子中。

标签: asp.net asp.net-web-api asp.net-web-api-routing


【解决方案1】:

ASP.NET Web API 中的路由分三个步骤工作:

  1. 将 URI 与路由模板匹配。
  2. 选择控制器。
  3. 选择一个动作。

框架在路由表中选择与 URI 匹配的第一个路由,在第二步或第三步失败的情况下没有“第二次猜测” - 只有 404。在您的情况下,两个 URI 始终与第一个路由匹配,因此second 从不使用。

为了进一步分析,我们假设第一条路线是:

api/{controller}/{action}/{userId}/{key}

您使用以下 URI 调用它:

http://&lt;domain&gt;/api/users/enrolments/a123/b456/

为了选择动作框架正在检查三件事:

  • 请求的 HTTP 方法。
  • 路由模板中的 {action} 占位符(如果存在)。
  • 控制器上的动作参数。

在这种情况下,{action} 部分将正确解析为enrolments,但框架将寻找带有userIdkey 参数的Enrolments 方法。您的方法有一个不匹配的 class 参数。这将导致 404。

为避免该问题,您必须制定更具体的路线(就像您所做的那样)或统一参数名称。

【讨论】:

  • 谢谢,我想我现在明白了。我将尝试几种不同的路由和方法签名组合,以确保我掌握了它。
【解决方案2】:

你只需要定义一个路由:

config.Routes.MapHttpRoute(
    name: "TestApi",
    routeTemplate: "api/{controller}/{action}/{userId}/{key}"
);

然后将您的控制器方法更改为以下内容:

[HttpGet]
public string Register(string userId, string key)
{
  return userId + "-" + key;
}

[HttpGet]
public string Details(string userId, string key)
{
  return userId + "-" + key
}

【讨论】:

  • 谢谢,我明白为什么会这样。但我不想更改参数的名称,我希望它们反映实际用途。
猜你喜欢
  • 2015-02-09
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 2012-07-15
  • 2017-06-26
  • 2011-03-09
  • 2018-05-13
  • 1970-01-01
相关资源
最近更新 更多