asp.net webapi2 捕获所有路由
asp.net webapi2 catch all route
如果在其他控制器上没有定义更具体的路由(即"api/myaccount/1/feature"),我希望执行与通用路由前缀("api/myaccount/1")匹配的所有路由,但是我当我这样做时出现以下异常:
Multiple controller types were found that match the URL. This can
happen if attribute routes on multiple controllers match the requested
URL.
如此处所述:
Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL 看来这不可能。
当找不到更好的路由时想要执行默认路由听起来很常见,那么我错过了什么?我需要在管道中挂钩还是什么...
仅供参考:我的 catch 一切正常 ("api/myaccount/1/{*uri}"),问题在于能够覆盖它。
原来这很简单,我只需要创建一个自定义控制器选择器并覆盖 GetControllerName 函数。该特定覆盖是必需的,因为您希望覆盖的方法:
HttpControllerDescriptor SelectController(HttpRequestMessage request)
不只是 return 描述符(如果找不到匹配项,则为 null),如您所料。该方法实际上为您处理请求并且 returns a 404 :/ 但是,一旦您意识到变通是微不足道的,并且我能够使用以下代码获得我想要的行为:
using System.Web.Http;
using System.Web.Http.Dispatcher;
public class CustomControllerSelector : DefaultHttpControllerSelector
{
public override string GetControllerName(HttpRequestMessage request)
{
var name = base.GetControllerName(request);
if(string.IsNullOrEmpty(name))
{
return "MyFeature"; //important not to include "Controller" suffix
}
return name;
}
}
并将其添加到您的配置中:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
config.Services.Replace(typeof(IHttpControllerSelector),
new CustomControllerSelector(config));
...
}
}
如果在其他控制器上没有定义更具体的路由(即"api/myaccount/1/feature"),我希望执行与通用路由前缀("api/myaccount/1")匹配的所有路由,但是我当我这样做时出现以下异常:
Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.
如此处所述: Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL 看来这不可能。
当找不到更好的路由时想要执行默认路由听起来很常见,那么我错过了什么?我需要在管道中挂钩还是什么...
仅供参考:我的 catch 一切正常 ("api/myaccount/1/{*uri}"),问题在于能够覆盖它。
原来这很简单,我只需要创建一个自定义控制器选择器并覆盖 GetControllerName 函数。该特定覆盖是必需的,因为您希望覆盖的方法:
HttpControllerDescriptor SelectController(HttpRequestMessage request)
不只是 return 描述符(如果找不到匹配项,则为 null),如您所料。该方法实际上为您处理请求并且 returns a 404 :/ 但是,一旦您意识到变通是微不足道的,并且我能够使用以下代码获得我想要的行为:
using System.Web.Http;
using System.Web.Http.Dispatcher;
public class CustomControllerSelector : DefaultHttpControllerSelector
{
public override string GetControllerName(HttpRequestMessage request)
{
var name = base.GetControllerName(request);
if(string.IsNullOrEmpty(name))
{
return "MyFeature"; //important not to include "Controller" suffix
}
return name;
}
}
并将其添加到您的配置中:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
config.Services.Replace(typeof(IHttpControllerSelector),
new CustomControllerSelector(config));
...
}
}