【问题标题】:.NET Core serving HTML file outside wwwroot can't load JS files.NET Core 在 wwwroot 之外提供 HTML 文件无法加载 JS 文件
【发布时间】:2017-07-07 15:52:37
【问题描述】:

我正在尝试不同的方法来保护具有 .NET Core 授权的 Angular CLI 应用程序。

为了使其尽可能安全,我希望防止所有 Angular CLI 输出文件公开可用,并将它们保存在 CLI 预配置的默认“dist”文件夹中。

我可以通过返回 PhysicalFileResult 从授权控制器加载 index.html...

public IActionResult Index()
{
    return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "dist", "index.html"),"text/HTML");
}

但是当页面加载时,我在所有 bundle.js 文件上都得到 404。

是否可以在不涉及静态文件中间件或公开文件的情况下以这种方式为应用程序提供服务(最好不必手动更改 index.html 中每个捆绑的 js 文件的 src)?

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc angular-cli


    【解决方案1】:

    看看这篇来自 asp.net 核心文档的文章(摘录如下):https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files#static-file-authorization


    【讨论】:

    • 我读到了,这促使我学习使用 PhysicalFile(),它返回一个 PhysicalFileResult。 medium.com/@tanaka_733/… 它可以工作,我可以从文件系统上的任何位置提供 index.html 文件,但 html 文件无法加载同一目录中的 javascript 文件。我觉得应该有一种方法可以从控制器操作中提供整个目录。
    【解决方案2】:

    只需将您的授权中间件放在静态中间件之前。

    // has to be first so user gets authenticated before the static middleware is called
    app.UseIdentity();
    
    app.Use(async (context, next) => 
    {
        // for pathes which begin with "app" check if user is logged in
        if(context.Request.Path.StartsWith("app") && httpContext.User==null)
        {
            // return "Unauthorized"
            context.Response.StatusCode = 401;
            return;
        }
    
        // If user is logged in, call next middleware
        await next.Invoke();
    });
    
    app.UseStaticFiles();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 2021-06-15
      • 2020-09-07
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      相关资源
      最近更新 更多