1:Startup 類 Configure 方法添加中間件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMyStaticImg();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
2:新建類 MyStaticImgExtensions
public static class MyStaticImgExtensions
{
public static IApplicationBuilder UseMyStaticImg(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException("app");
}
return UseMiddlewareExtensions.UseMiddleware<MyStaticImgMiddleware>(app, Array.Empty<object>());
}
}
3:新建類 MyStaticImgMiddleware
public class MyStaticImgMiddleware
{
private readonly RequestDelegate _next;
public MyStaticImgMiddleware(RequestDelegate next)
{
this._next = next;
}
/// <summary>
/// 中間件被調用的時候執行
/// </summary>
/// <param name="context">http請求</param>
/// <returns></returns>
public Task Invoke(HttpContext context)
{
//請求的路徑
var path = context.Request.Path.Value;
//如果請求中有png圖片,返回圖片
if (path.Contains(".png"))
{
var mypath = path.TrimStart('/');
//返回一張圖片
return context.Response.SendFileAsync(mypath);
}
var task = this._next(context);
return task;
}
}
4:注意
圖片的屬性要設置爲始終複製