如何解决在ASP.NET Core中找不到图像时设置默认图像
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                如何解决在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
總結
以上是生活随笔為你收集整理的如何解决在ASP.NET Core中找不到图像时设置默认图像的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: .NET Core AWS S3云存储
- 下一篇: MiniProfiler,一个.NET简
