.net core 中间件的使用
程序员文章站
2023-12-28 14:55:52
...
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:注意
图片的属性要设置为始终复制