3

I have these two routes defined:

routes.MapRoute(
    name: "GetVoucherTypesForPartner",
    url: "api/Partner/{partnerId}/VoucherType",
    defaults: new { controller = "Partner", action = "GetVoucherTypesForPartner"}
);

routes.MapRoute(
    name: "Default",
    url: "api/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);

In my PartnerProfile controller, I have 2 methods:

public Partner Get(string id)
{ }

public IEnumerable<string> GetVoucherTypesForPartner(string id)
{ }

If I hit the url ~/api/Partner/1234 then, as expected, the Get method is called.
However, if I hit the url ~/api/Partner/1234/VoucherType then the same Get method is called. I am expecting my GetVoucherTypesForPartner to be called instead.

I'm pretty sure something in my route setup is wrong...

4

1 回答 1

2

您似乎映射了标准 MVC 路由,而不是 Web API 路由。有很大的不同。标准路由由派生自Controller该类的控制器使用,但如果您使用 ASP.NET Web API 并且您的控制器是从该ApiController类型派生的,那么您应该定义 HTTP 路由。

你应该在你的~/App_Start/WebApiConfig.cs而不是你的~/App_Start/RouteConfig.cs.

所以请继续:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "GetVoucherTypesForPartner",
            routeTemplate: "api/Partner/{partnerId}/VoucherType",
            defaults: new { controller = "Partner", action = "GetVoucherTypesForPartner" }
        );

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

接着:

public class PartnerController : ApiController
{
    public Partner Get(string id)
    {
        ...
    }

    public IEnumerable<string> GetVoucherTypesForPartner(string partnerId)
    {
        ...
    }
}

注意事项:

  • 我们定义了 HTTP 路由而不是标准的 MVC 路由
  • GetVoucherTypesForPartner必须调用操作所采用的参数,partnerId而不是id为了尊重您的路由定义并避免任何混淆
于 2013-04-24T14:30:19.977 回答