如何配置ngRoute去除#!后缀,优化ASP.NET MVC项目URL格式?
解决AngularJS路由去掉#!/后缀的问题
我来帮你搞定这个干净URL的需求,要去掉AngularJS路由的#!/后缀,需要结合Angular的HTML5模式和ASP.NET MVC的路由转发配置,具体步骤如下:
1. 启用AngularJS的HTML5模式
修改你的app.js路由配置,注入$locationProvider并开启html5Mode,这样Angular会使用HTML5 History API替代哈希bang路由:
app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) { // 启用HTML5模式,移除#!/前缀 $locationProvider.html5Mode(true); $routeProvider .when("/Login", { templateUrl: "/Partials/LoginPartial.html", controller: "LogInController" }) .when("/CreateAccount", { templateUrl: "/Partials/CreateAccountPartial.html", controller: "CreateAccountController" }) .otherwise({ redirectTo: "/Login" }); }])
2. 添加Base标签到视图
在Login.cshtml的<head>中加入<base>标签,帮助Angular正确解析相对路由路径。因为你的入口视图是Login/Login,所以base href要对应这个路径:
<head> <!-- 其他页面资源(CSS、JS) --> <base href="@Url.Content("~/Login/Login/")" /> </head>
3. 修改前端导航链接
去掉链接中的#!/前缀,直接使用干净的路径:
<ul class="one-page-menu"> <li class="current"><a href="CreateAccount"><div>Create Account</div></a></li> <li><a href="Login"><div>Login</div></a></li> </ul>
4. 配置ASP.NET MVC的Catch-All路由
这一步是核心,否则用户刷新页面或直接访问干净URL时会出现404错误(MVC会尝试匹配不存在的Action)。打开App_Start/RouteConfig.cs,添加一个优先于默认路由的Catch-All规则,把所有Login/Login下的子路径转发到Login/Login Action:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // 处理Angular HTML5路由的Catch-All规则 routes.MapRoute( name: "AngularRoutes", url: "Login/Login/{*path}", // 匹配Login/Login下的所有子路径 defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
5. 配置IIS重写规则(部署时需要)
如果你的应用部署在IIS上,还需要在web.config中添加重写规则,确保服务器将非文件/目录的请求转发到入口视图:
<system.webServer> <rewrite> <rules> <rule name="AngularJS Routes" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <!-- 排除真实存在的文件和目录 --> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> <!-- 排除API路由(如果你的应用有API的话) --> <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> <!-- 只处理Login/Login下的路由 --> <add input="{REQUEST_URI}" pattern="^/Login/Login" /> </conditions> <!-- 将请求重写到入口视图 --> <action type="Rewrite" url="/Login/Login" /> </rule> </rules> </rewrite> </system.webServer>
完成这些配置后,点击Login链接时URL会变成http://localhost:18223/Login/Login,点击Create Account时会变成http://localhost:18223/Login/Login/CreateAccount,页面刷新、直接访问这些URL也都能正常加载对应视图。
内容的提问来源于stack exchange,提问作者stack questions
相关产品推荐
相关产品推荐

