免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

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

dotNET跨平臺(tái) 今天

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

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開發(fā)組件。

實(shí)現(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


本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
ASP.NET中文件上傳下載方法集合
巧用asp.net 過(guò)濾所有的Response請(qǐng)求并替換部分內(nèi)容,徹底解決MVC虛擬路徑問(wèn)題.
[C# 多線程處理系列專題七——對(duì)多線程的補(bǔ)充
ASP.NET Core Web API 流式返回,逐字顯示
ASP.NET Core MVC 從入門到精通之路由
ASP.NET Core 開發(fā)- Entity Framework (EF)
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服