You need to enable JavaScript to run this app. ASP.NET MVC自定义路由匹配特定JSON地址返回404如何修复
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC自定义路由匹配特定JSON地址返回404如何修复

问题根因

404报错不是路由配置的URL匹配路径错误,是请求在到达MVC管线前就被多层逻辑拦截了,具体问题点:

  • IIS静态文件模块优先拦截带.json后缀的请求,因为找不到对应的实体文件直接返回404,根本不会转发到MVC路由
  • MVC路由默认 RouteExistingFiles 属性为false,会自动跳过所有匹配静态文件规则的请求,不执行自定义路由匹配
  • IIS默认请求过滤规则会把点开头的路径段(如.well-known)识别为隐藏目录,直接拒绝访问
  • 隐藏报错点:MVC的Json()方法默认禁止GET请求访问,抛出的异常可能被自定义错误页伪装成404返回
分步修复操作

1. 调整路由配置

在RegisterRoutes方法开头开启路由对匹配静态文件规则请求的处理,保持自定义验证路由在默认路由之前的匹配优先级:

public static void RegisterRoutes(RouteCollection routes)
{
    // 开启路由对静态文件匹配请求的接管能力
    routes.RouteExistingFiles = true;
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Azure domain registration",
        ".well-known/microsoft-identity-association.json",
        new { controller = "Hosting", action = "MicrosoftIdentityAssociation" }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

2. 修正Controller的Action逻辑

补全Json返回的GET访问权限,避免接口抛出访问异常:

public class HostingController : Controller
{
    [OutputCache(Duration = 100, VaryByParam = "none")]
    public ActionResult MicrosoftIdentityAssociation()
    {
        var clientId = WebConfigurationManager.AppSettings["ClientId"];
        return Json(new
        {
            associatedApplications = new[]
            {
                new { applicationId = clientId }
            }
        }, JsonRequestBehavior.AllowGet);
    }
}

3. 修改web.config解除IIS层拦截

仅针对目标验证路径做单独配置,不影响全局静态资源的正常访问:

<configuration>
  <!-- 全局请求过滤规则调整 -->
  <system.webServer>
    <security>
      <requestFiltering>
        <allowDoubleEscaping>true</allowDoubleEscaping>
        <hiddenSegments>
          <!-- 移除对.well-known路径段的隐藏拦截 -->
          <remove segment="well-known" />
        </hiddenSegments>
      </requestFiltering>
    </security>
  </system.webServer>

  <!-- 仅给目标JSON验证路径单独配置处理器 -->
  <location path=".well-known/microsoft-identity-association.json">
    <system.webServer>
      <handlers>
        <!-- 针对该路径移除静态文件拦截,把请求转交给ASP.NET路由管线 -->
        <remove name="StaticFile" />
        <add name="WellKnownJsonRouteHandler" 
             path="*" 
             verb="GET" 
             type="System.Web.Handlers.TransferRequestHandler" 
             preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>
</configuration>

配置完成后重启站点,访问目标URL即可正常动态返回对应格式的JSON内容。


内容的提问来源于stack exchange,提问作者Steve B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 14:45:08