.Net Core 2 & AngularJS SPA 不起作用



我一直在将一个项目从.NET Framework迁移到.NET Core 2,这个过程比预期的要顺利,但是当我认为我已经克服了最困难的挑战时,我无法在我的生命中让SPA方面工作。

当我启动应用程序时,只要我转到根目录 (https://localhost:5001( 并且我可以使用 Angular 路由进行导航,它就可以正常工作。但是,如果我尝试通过路由加载页面,例如。https://localhost:5001/login,我收到一个通用的Chrome 404"找不到此本地主机页面"。

我的index.html在目录MyApp/Pages/中,我的客户端代码在MyApp/wwwroot/app/中。将index.html移动到wwwroot文件夹中时,我什么也得不到。

在我的Startup.cs中,这是我的设置方式:

public class Startup
{
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
} 
app.UseHttpsRedirection();
app.UseStaticFiles();
var defaultFileOptions = new DefaultFilesOptions();
defaultFileOptions.DefaultFileNames.Clear();
defaultFileOptions.DefaultFileNames.Add("/index.html");
app.UseDefaultFiles(defaultFileOptions);
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
context.Response.StatusCode = 200;
await next();
}
});
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
}

我尝试了许多指南,但似乎我能找到的大多数指南都非常过时,或者在尝试在帖子中使用方法时,它们是我没有的方法。非常感谢任何帮助,因为我非常想完成迁移并继续从事该项目。

这里的问题是你有一个SPA,而Angular有自己的路由,但是当你尝试使用像这样的URL时,https://localhost:5001/login,这个路由由MVC而不是Angular提供,MVC找不到合适的控制器并返回404。

你应该做的是返回index.html以响应此类请求,以便Angular路由可以处理它。你可以看看这篇文章:

https://www.toptal.com/angular/angular-5-asp-net-core

事实证明,我的问题在于我处理 404 的方式。我正在我的 Startup.cs 中执行context.Request.Path = "/index.html";,但它仍然无法解析 html 文件,所以我让它重定向回根路径:

app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value))
{
// This is what I changed. I need to resolve to "/" instead of "/index.html"
context.Request.Path = "/";
context.Response.StatusCode = 200;
await next();
}
});

感谢@Anton Danylov的建议,指出我重新审视那段代码。

从以下代码中使用:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}

点击链接:ASP.NET 核心中的应用程序启动

最新更新