You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RouteAttribute单个路由失效:Route1请求返回404问题排查

Route1 始终返回404的原因及解决办法

1. Unity依赖容器未注册控制器

你的WebApiConfig中使用Unity作为依赖解析器,如果Unity容器没有注册IntegrationController,Web API就算匹配到路由,也无法创建控制器实例,最终返回404。

解决办法:

  • 在UnityConfig.Configuracoes中手动注册控制器:
    container.RegisterType<IntegrationController>();
    
  • 或者让Unity自动注册所有ApiController类型:
    container.RegisterTypes(
        AllClasses.FromLoadedAssemblies().Where(type => typeof(ApiController).IsAssignableFrom(type)),
        WithMappings.FromMatchingInterface,
        WithName.Default,
        WithLifetime.Transient);
    

2. IIS请求处理模块配置异常

如果IIS未正确配置无扩展名请求的处理模块,Web API的api/xxx类型请求会被当成静态文件处理,直接返回404。

解决办法:

  • 确认项目Web.config的<system.webServer>节点下包含以下配置:
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    
  • 检查IIS是否安装ASP.NET 4.0,且应用程序池使用集成模式。

3. 属性路由注册顺序错误

虽然你调用了config.MapHttpAttributeRoutes(),但如果这行代码放在依赖解析器配置之前,可能导致属性路由无法正确加载控制器的路由规则。

解决办法:

  • 调整WebApiConfig的代码顺序,先配置依赖解析器,再注册属性路由:
    public static void Register(HttpConfiguration config)
    {
        config.Services.Add(typeof(IExceptionLogger), new CustomExceptionLogger());
    
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
        // 先配置依赖解析器
        config.DependencyResolver = new UnityResolver(UnityConfig.Configuracoes);
        // 再注册属性路由
        config.MapHttpAttributeRoutes();
    }
    

4. 全局路由冲突(移除其他路由仍可能存在)

如果项目中存在其他全局路由(比如传统约定式路由),可能和属性路由冲突,导致Route1无法被匹配。

解决办法:

  • 检查WebApiConfig中是否添加了默认路由,不需要的话直接删除;如果需要保留,注意属性路由优先级更高,但如果默认路由模板过于宽泛,可能会抢占匹配权。

5. 请求HTTP方法不匹配

Route1标记了[HttpGet],但如果实际请求使用POST/PUT等其他方法,Web API会因方法不匹配返回404。

解决办法:

  • 确保使用GET方法访问api/integration/nfse。

内容的提问来源于stack exchange,提问作者Max Bündchen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:28:13