当你在 AngularJS 和 ASP.NET 构建的单页应用(SPA)中刷新页面时出现404错误,这是因为:
$locationProvider.html5Mode(true)
启用了HTML5路由模式,这个问题会更明显在ASP.NET中,你需要配置一个通配路由,将所有请求重定向到你的SPA入口点(通常是index.html):
// 在WebApiConfig.cs或RouteConfig.cs中
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// 其他API路由配置
// 通配路由 - 必须放在最后
routes.MapRoute(
name: "SPA-Fallback",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
}
在web.config中添加URL重写规则:
<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" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
确保你的AngularJS应用正确配置了HTML5模式和基础URL:
angular.module('myApp', [])
.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
}]);
并在index.html的<head>
中添加:
<base href="/">
对于ASP.NET Core应用,在Startup.cs中配置:
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
这种配置特别适用于:
通过以上配置,你的AngularJS和ASP.NET单页应用应该能够正确处理页面刷新操作,不再返回404错误。