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

ASP.NET Core(.NET8)迁移后cshtml生成JS路由报400错误求助

排查与解决ASP.NET Core 8中路由脚本请求400 Bad Request问题

可能原因及对应解决方案

1. 确认默认路由名称"Default"是否存在

ASP.NET Core 8中不再自动配置传统的"Default"路由,需要手动在Program.cs中添加:

app.MapControllerRoute(
    name: "Default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

如果未配置该路由,Url.RouteUrl("Default")会生成无效URL,直接导致请求400。

2. 检查视图文件位置与路径

确保_Routes.cshtml位于正确位置:

  • 若放在Views/Home文件夹下,控制器中return View("_Routes")可正常找到;
  • 若放在Views/Shared文件夹下,需修改控制器代码指定完整路径:
    return View("~/Views/Shared/_Routes.cshtml");
    

视图路径错误会导致视图无法渲染,间接引发请求异常。

3. 统一Content-Type设置方式

移除_Routes.cshtml中的Context.Response.ContentType = "text/javascript";,仅保留控制器中的设置即可。重复设置可能导致响应头异常:
修改后的_Routes.cshtml:

@{ Layout = ""; }
var commonRoutes = {
  userList: '@Url.RouteUrl("Default", new { Controller = "User", Action = "GetUserList" })',
  location: '@Url.RouteUrl("Default", new { Controller = "User", Action = "GetUserLocations" })',
}

4. 验证Anti-Forgery配置(若启用全局验证)

如果项目全局启用了Anti-Forgery验证(比如基类控制器添加了[ValidateAntiForgeryToken]),需确保GET请求被排除。在GetRoutesAction上添加[IgnoreAntiforgeryToken]特性:

[IgnoreAntiforgeryToken]
public IActionResult GetRoutes()
{
    Response.ContentType = "text/javascript";
    return View("_Routes");
}

script标签的src请求为GET方法,默认不会携带Anti-Forgery令牌,全局验证会直接触发400错误。

5. 检查URL生成是否正确

在_Layout视图中临时输出生成的URL,确认有效性:

@Url.RouteUrl("Default", new { Controller = "Home", Action = "GetRoutes" })

若输出为空或错误路径,说明路由配置存在问题,回到第一步修正路由。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:12:38