【问题标题】:Web API route for different parameter types不同参数类型的 Web API 路由
【发布时间】:2013-12-01 01:39:38
【问题描述】:

试图了解 Web API 路由。

我有以下两个具有不同方法/动作的控制器

 public class MerchantController : ApiController
    {
        [HttpGet]
        [ActionName("GetSuggestedMerchants")]
        public IEnumerable<Merchant> GetSuggestedMerchants(string name)
        {
           ....

    public class PortalMerchantController : ApiController
    {
        [HttpGet]
        [ActionName("GetNPortalMerchants")]
        public IEnumerable<PortalMerchantDto> GetNPortalMerchants(int id)
        {
          ...

我已经映射了这两条路线:

        config.Routes.MapHttpRoute(
           name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
         name: "ActionApiTwoParams",
          routeTemplate: "api/{controller}/{action}/{name}"
          );

打电话

$http.get("api/PortalMerchant/GetNPortalMerchants/26") 

工作正常,但调用

$http.get("api/Merchant/GetSuggestedMerchants/SomeName")

没有被路由并失败:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:2769/api/Merchant/GetSuggestedMerchants/SomeName'.","MessageDetail":"No action was found on the controller 'Merchant' that matches the request."}

我认为我需要两个根,因为这两种方法的参数名称和类型不同。谁能建议为什么第二个没有被路由?

【问题讨论】:

  • 我猜它一定是使用第一条路由 $http.get("api/Merchant/GetSuggestedMerchants/SomeName") 这可以解释为什么在 Merchant 控制器上没有找到任何操作(因为没有方法它需要一个 ID 参数)但是为什么在指定参数名称时它会使用第一个路由而不是第二个路由?

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


【解决方案1】:

路由采用与 URL 匹配的第一个路由。

您的网址不包含命名参数。仅包含参数值。

您需要定义更严格的routeTemplates。喜欢:

    config.Routes.MapHttpRoute(
     name: "PortalMerchantAPI",
      routeTemplate: "api/PortalMerchant/{action}/{name}"
      );
    config.Routes.MapHttpRoute(
     name: "MerchantAPI",
      routeTemplate: "api/Merchant/{action}/{id}"
        defaults: new { id = RouteParameter.Optional }
      );
    config.Routes.MapHttpRoute(
       name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

路线的顺序很重要

【讨论】:

  • 你也可以看看这个场景的属性路由。
猜你喜欢
  • 2020-02-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多