如果其他 Controller 上没有定义更多特定路由(即“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看来这不可能。
在找不到更好的路由时想要执行默认路由听起来很常见,那么我错过了什么?我需要将管道钩在较低的位置还是什么...
仅供引用:我的所有功能都工作正常(“api/myaccount/1/{*uri}”),只是能够覆盖它才是问题所在。
最佳答案
事实证明这非常简单,我只需要创建一个自定义 Controller 选择器并覆盖 GetControllerName 函数。该特定重写是必需的,因为您希望重写的方法:
HttpControllerDescriptor SelectController(HttpRequestMessage request)
不只是返回描述符(如果找不到匹配项则返回 null),正如您所期望的那样。该方法实际上为您处理请求并返回 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));
...
}
}
关于c# - asp.net webapi2 捕获所有路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33641143/