日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

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

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

dotNET跨平臺(tái) 今天

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

UP技術(shù)控

UP技術(shù)控

不止IT 還有生活

背景

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

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

先決條件

  • Visual Studio 2017或更高版本。

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

實(shí)現(xiàn)方式

1、Startup 文件

app.UseDefaultImage(defaultImagePath: Configuration.GetSection("defaultImagePath").Value);

2、新建類(lèi)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圖片即可

開(kāi)源地址

https://github.com/conanl5566/Sampleproject


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

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶(hù) 評(píng)論公約

    類(lèi)似文章 更多