asp.net 核心不加载静态文件

Pau*_*ulo 0 c# .net-core kestrel-http-server asp.net-core

我有一个带有以下代码的应用程序 .NET core 2.1:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "Assets")),
            RequestPath = "/Assets"
        });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
Run Code Online (Sandbox Code Playgroud)

和我的结构文件夹:

在此处输入图片说明

但这些网址都没有打开图像:

“my-website.com/images/snes/alien.jpg”

“my-website.com/wwwroot/images/snes/alien.jpg”

“my-website.com/Assets/Snes/alien.jpg”

有人知道出了什么问题吗?

编辑:这是 CurrentDirectoy() 方法获取的文件夹(显然是正确的):

在此处输入图片说明

Edit2:使用此代码在 localhost 上工作,但在我在 azure 上发布时却没有:

 app.UseFileServer(
        new FileServerOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"))
        });
Run Code Online (Sandbox Code Playgroud)

Chr*_*rdt 6

您所在的工作目录很可能与您想象的不同。请通过在 foo 上设置断点来检查这一点:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var foo = Directory.GetCurrentDirectory();
}
Run Code Online (Sandbox Code Playgroud)

解决方案取决于您如何启动应用程序。

如果您通过 Visual Studio 执行此操作,您可能在项目属性中设置了另一个工作目录?

项目属性

如果通过命令行,您需要cd到您的项目根目录。

另一种解决方案是使用程序集目录

// get the directory
var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
var assetDirectory = Path.Combine(assemblyDirectory, "Assets"));

// use it
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(assetDirectory),
    RequestPath = "/Assets"
});
Run Code Online (Sandbox Code Playgroud)


小智 6

使用IHostingEnvironment

app.UseStaticFiles(new StaticFileOptions
{
     FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Assets")),
            RequestPath = "/Assets"
});
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您使用的是可视化代码,那么您必须在文件数组的cwd参数中设置您的工作目录。见附件截图。configurationlunch.json

在此处输入图片说明