C# 正在忽略Web API路由
我定义了这两条路线:C# 正在忽略Web API路由,c#,asp.net-mvc-4,asp.net-web-api,C#,Asp.net Mvc 4,Asp.net Web Api,我定义了这两条路线: routes.MapRoute( name: "GetVoucherTypesForPartner", url: "api/Partner/{partnerId}/VoucherType", defaults: new { controller = "Partner", action = "GetVoucherTypesForPartner"} ); routes.MapRoute( name: "Default", url: "a
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}
);
在我的PartnerProfile
控制器中,我有两种方法:
public Partner Get(string id)
{ }
public IEnumerable<string> GetVoucherTypesForPartner(string id)
{ }
公共合作伙伴获取(字符串id)
{ }
公共IEnumerable GetVoucherTypesPartner(字符串id)
{ }
如果我点击url~/api/Partner/1234
,那么,正如预期的那样,将调用Get
方法。但是,如果我点击url
~/api/Partner/1234/VoucherType
,则调用相同的Get
方法。我希望调用我的GetVoucherTypesForPartner
我很确定我的路线设置有问题…您似乎映射了标准MVC路线,而不是Web API路线。这有很大的区别。标准路由由派生自
Controller
类的控制器使用,但如果您使用的是ASP.NET Web API,并且您的控制器派生自ApiController
类型,则应定义HTTP路由
您应该在~/App\u Start/WebApiConfig.cs
中执行此操作,而不是在~/App\u 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)
{
...
}
}
公共类PartnerController:ApicController
{
公共伙伴获取(字符串id)
{
...
}
public IEnumerable GetVoucherTypesPartner(字符串partnerId)
{
...
}
}
注意事项:
- 我们定义了HTTP路由,而不是标准的MVC路由
- 必须调用
操作所使用的参数GetVoucherTypesForPartner
,而不是partnerId
,以尊重路由定义并避免任何混淆id