微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何解决在ASP.NET Core中找不到图像时设置默认图像

目录

背景

先决条件

实现方式

开源地址


 

背景

web上如果图片不存在一般是打xx,这时候一般都是会设置认的图片代替。现在用中间件的方式实现统一设置, 一次设置,全部作用 。

此示例演示如何解决在ASP.NET Core中找不到图像时设置认图像

先决条件

  • Visual Studio 2017或更高版本。

  • 启用Visual Studio的ASP.NET Core开发组件。

实现方式

1、Startup 文件

app.UseDefaultimage(defaultimagePath: Configuration.GetSection("defaultimagePath").Value);

2、新建类DefaultimageMiddleware

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Http;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Threading.Tasks;

 

namespace conan.Saas.Framework.Middlewares

{

    public class DefaultimageMiddleware

    {

        private readonly RequestDelegate _next;

 

        public static string DefaultimagePath { get; set; }

 

        public DefaultimageMiddleware(RequestDelegate next)

        {

            this._next = next;

        }

 

        public async Task Invoke(HttpContext context)

        {

            await _next(context);

            if (context.Response.StatusCode == 404)

            {

                var contentType = context.Request.Headers["accept"].ToString().ToLower();

                if (contentType.StartsWith("image"))

                {

                    await SetDefaultimage(context);

                }

            }

        }

 

        private async Task SetDefaultimage(HttpContext context)

        {

            try

            {

                string path = Path.Combine(Directory.GetCurrentDirectory(), DefaultimagePath);

 

                FileStream fs = File.OpenRead(path);

                byte[] bytes = new byte[fs.Length];

                await fs.ReadAsync(bytes, 0, bytes.Length);

                //this header is use for browser cache, format like: "Mon, 15 May 2017 07:03:37 GMT".

                //context.Response.Headers.Append("Last-Modified", $"{File.GetLastWriteTimeUtc(path).ToString("ddd, dd MMM yyyy HH:mm:ss")} GMT");

 

                await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);

            }

            catch (Exception ex)

            {

                await context.Response.WriteAsync(ex.Message);

            }

        }

    }

 

    public static class DefaultimageMiddlewareExtensions

    {

        public static IApplicationBuilder UseDefaultimage(this IApplicationBuilder app, string defaultimagePath)

        {

            DefaultimageMiddleware.DefaultimagePath = defaultimagePath;

 

            return app.UseMiddleware<DefaultimageMiddleware>();

        }

    }

}

3、appsettings.json 添加路径

 "defaultimagePath": "wwwroot\\Defaultimage.png",

 4、最后在wwwroot放张Defaultimage.png图片即可

开源地址

https://github.com/conanl5566/Sampleproject

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐