c# - asp.net webapi2 捕获所有路由

标签 c# asp.net asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

如果其他 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/

相关文章:

c# - CA2000 方法使用 "using",但不使用 try/finally

c# - 如何在C#中更改音调

c# - ASP.NET 捕获并替换 Global.asax 中的输出

c# - 异步方法调用和模拟

c# - 远程连接到 .net 核心自托管 web api

c# - CompareTo 方法不起作用,它不会从 Album 类中获取 AlbumName - 我认为是 IComparable 问题

C# 有理由不再使用 ArrayList 而不是 List<T> 吗?

c# - EntityFramework 更新或插入中文或非英文文本

c# - 在不接触磁盘的情况下读取多部分/表单数据

logging - 将 log4net 与 WebApi 结合使用 - 在整个实例中保持相同的相关 ID