小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

如何解決在ASP.NET Core中找不到圖像時設(shè)置默認(rèn)圖像

 風(fēng)聲之家 2021-05-02

dotNET跨平臺 今天

以下文章來源于UP技術(shù)控 ,作者conan5566

UP技術(shù)控

UP技術(shù)控

不止IT 還有生活

背景

web上如果圖片不存在一般是打xx,這時候一般都是會設(shè)置默認(rèn)的圖片代替?,F(xiàn)在用中間件的方式實現(xiàn)統(tǒng)一設(shè)置, 一次設(shè)置,全部作用 。

此示例演示如何解決在ASP.NET Core中找不到圖像時設(shè)置默認(rèn)圖像

先決條件

  • Visual Studio 2017或更高版本。

  • 啟用Visual Studio的ASP.NET Core開發(fā)組件。

實現(xiàn)方式

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


    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多