【问题标题】:ASP.net Core Static Files - How to return a default file (per extension) if the one requested doesn't exist?ASP.net Core 静态文件 - 如果请求的文件不存在,如何返回默认文件(每个扩展名)?
【发布时间】:2018-07-19 08:01:09
【问题描述】:

根据this official guide,我了解如何在 ASP.net Core Web 应用程序上设置服务静态文件。如果他们请求的图像(例如)不存在,我不想返回 default.html 页面。

在Startup.cs 的Configure(IApplicationBuilder app, IHostingEnvironment env); 中,我有app.UseStaticFiles()。

我的Program.cs 文件:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseDefaultServiceProvider(options =>
                options.ValidateScopes = false)
            .Build();
}

默认情况下,这将允许我将文件存储到我的应用程序中的 wwwroot 文件夹并提供文件。

如果我在wwwroot中有图片文件mypic.jpg,我可以打开浏览器去http://localhost:53020/mypic.jpg查看。

假设我已经部署了这个应用程序,并且有人要转到他们的浏览器并转到,或者在他们的网页中,将img 的src 设置为等于http://mydeployedsite.com/nonexistentpic.jpg,他们会得到一个 404,或者默认页面,取决于我选择的页面。但是,我想提供一个图形指示“找不到文件”的图像。如果请求的文件不存在,我在链接的该指南中没有看到任何地方都可以选择为每个扩展名提供默认文件。

我可能不得不为我想要的东西编写中间件。我了解如何编写基本的中间件,但是在这样的中间件中,我不知道如何拦截来自静态文件中间件的 404 响应。或者,该官方文档中未包含的静态文件中间件中可能有更多选项。除了通过路由和控制器功能提供文件之外,我还可以采取哪些其他方法?

【问题讨论】:

    标签: asp.net-core static-files


    【解决方案1】:

    静态文件中间件中没有选项可以满足您的要求。
    我认为您可以拦截 404 响应,并检查该请求是否是对图像的请求。 这是一个简单的代码

            app.Use(async (context, next) => {
                await next.Invoke();
                //handle response
                //you may also need to check the request path to check whether it requests image
                if(context.Response.StatusCode == 404 && context.Request.Path.Value.Contains(".jpg"))
                {
                    context.Response.Redirect("/DefaultImage.gif"); //path in wwwroot for default image
                }
            });
            app.UseStaticFiles();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 2013-07-30
      • 2017-02-10
      相关资源
      最近更新 更多