.NET Core 在 wwwroot 之外提供 HTML 文件无法加载 JS 文件 [英] .NET Core serving HTML file outside wwwroot can't load JS files

查看:43
本文介绍了.NET Core 在 wwwroot 之外提供 HTML 文件无法加载 JS 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am experimenting with different ways to secure an Angular CLI app with .NET Core Authorization.

为了尽可能安全,我希望所有的 Angular CLI 输出文件都不公开可用,并将它们保存在 CLI 预先配置的默认dist"文件夹中.

To make it as secure as possible, I would like to keep all of the Angular CLI output files from being publicly available and keep them in the default "dist" folder preconfigured by the CLI.

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

I can load the index.html from an authorized controller by returning a PhysicalFileResult...

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

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

But I get 404s on all of the bundle.js files when the page loads.

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

Is it possible to serve the app this way without involving the static file middleware or making the files publicly available (preferably without having to manually change the src for each bundled js file in index.html)?

推荐答案

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

Just place your authorization middleware before the static one.

// 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();

这篇关于.NET Core 在 wwwroot 之外提供 HTML 文件无法加载 JS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆