2017-07-07 342 views
0

我正在嘗試使用不同的方法來保護帶有.NET Core Authorization的Angular CLI應用程序。在wwwroot外部提供HTML文件的.NET Core無法加載JS文件

爲了使其儘可能安全,我希望保持所有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)?

回答

0

看看這篇文章從asp.net核心文檔(包括下面摘錄):https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files#static-file-authorization


enter image description here

+0

,我讀了,這促使我要學會用PhysicalFile(),它返回一個PhysicalFileResult。 https://medium.com/@tanaka_733/static-file-authorization-in-asp-net-core-mvc-26c1069073c1它的工作原理,我可以從文件系統的任何地方提供index.html文件,但html文件無法加載位於同一目錄中的JavaScript文件。我覺得應該有一種方法來從控制器操作中提供整個目錄。 – David

0

只需將您的授權中間件靜態的人之前。

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