Aspnet Core.角.静态页面和 html5 模式



我正在构建AngularJs和WebApi应用程序,usin Aspnet Core rc1。我在返回静态index.html文件时遇到问题。我已经尝试了几种方法。第一种方法是在Startup.cs中使用此类代码

app.UseFileServer();
app.UseMvc();

这样,如果我调用http://localhost:29838(根网址),它就可以工作。但是如果我继续http://localhost:29838/books/books根是我使用 ng-route 定义的角度根,我使用的是 html5 模式)并更新页面,服务器当然会返回 404 错误。

然后,我 https://dzone.com/articles/fixing-html5mode-and-angular 阅读了这篇文章。我尝试在web.config中使用重写模块方法/一切正常。但我不喜欢这种方法。据我了解,它仅适用于 IIS。

最后,我尝试使用文章中描述的第一种方法(当Home/Index返回 html 文件时).controller 代码是:

public ActionResult Index()
{
    return File("~/index.html", "text/html");
}

Startup.cs是:

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

使用这种方法,我有这样的错误:Refused to load the script 'http://localhost:29838/libs/jquery/dist/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'unsafe-inline'".我无法克服这一点。我做错了什么?

尝试使用AspnetCore.SpaServices,它们为您提供合法的HTML5水疗后备。像这样:

app.UseStaticFiles();
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });
});

此库修复了 SPA 回退的所有问题。

如果您使用的是具有服务器端呈现或某些服务器逻辑的 MVC 页面,@Andrei提到的 SpaServices 非常有用。

如果你在服务器端没有任何逻辑,并且你不需要它,你可以执行以下操作:

app.Use(async (context, next) => 
{ 
    await next(); 
    if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) 
    { 
        context.Request.Path = "/index.html"; 
        await next(); 
    } 
}) 
.UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new List<string> { "index.html" } }) 
.UseStaticFiles()

代码段的作用是查找服务器端不存在的页面,并将它们重定向到"/index.html"。如果您有其他入口点文件,则可以更改 URL。此外,如果请求的文件具有扩展名,则提供该文件以允许在客户端上呈现javascript,css,html等。

你也可以看看这里: https://code.msdn.microsoft.com/How-to-fix-the-routing-225ac90f

最后。我已经找到了解决方案。为了安全起见,我使用OpenIdConnect.Server.在示例项目中,作者使用NWebsec.Middleware .我刚刚从此示例项目中复制了 csp 设置

 app.UseCsp(options => options.DefaultSources(configuration => configuration.Self())
                                     .ImageSources(configuration => configuration.Self().CustomSources("data:"))
                                     .ScriptSources(configuration => configuration.UnsafeInline())
                                     .StyleSources(configuration => configuration.Self().UnsafeInline()));

请注意,作者在 ScripSources() 之后拼错了调用.Self()方法。我没有注意到!!复制和粘贴时要小心

最新更新