.NET Core serving HTML file outside wwwroot can't load JS files

江枫思渺然 提交于 2019-12-12 04:03:50

问题


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

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.

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");
}

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

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)?


回答1:


Take a look at this article from the asp.net core docs (excerpt included below): https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files#static-file-authorization





回答2:


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


来源:https://stackoverflow.com/questions/44975048/net-core-serving-html-file-outside-wwwroot-cant-load-js-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!