当前位置:网站首页>. net 5 Web custom middleware implementation returns the default picture
. net 5 Web custom middleware implementation returns the default picture
2022-04-23 03:18:00 【Pingshan CP3】
background : During the request for a large number of map tiles , There may be a loss of tiles , At this time, you need to display the default tile image on the map , Previously, it was implemented in the front-end related map package , It is now implemented in the background. When the request for tiles fails , Returns the default tile image , And support the default picture configuration .
solve :
1. establish .net 5 Web project
2. introduce Microsoft.Extensions.Configuration, For reading appsettings.json
3. Create a new middleware class DefaultImageMiddleware
public class DefaultImageMiddleware
{
private readonly RequestDelegate _next;
public static string DefaultImagePath { get; set; }
/// <summary>
/// When the pipeline execution reaches our middleware, it receives... From the previous middleware RequestDelegate entrust
/// </summary>
/// <param name="next"></param>
/// <param name="defaultImagePath"> Default tile picture </param>
public DefaultImageMiddleware(RequestDelegate next, string defaultImagePath)
{
this._next = next;
DefaultImagePath = defaultImagePath;
}
/// <summary>
/// to HTTP Request the pipeline to join the business
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
await _next(context);// take context Pass on to the next middleware
if (context.Response.StatusCode == 404)
{// Request resources 404
var contentType = context.Request.Headers["accept"].ToString().ToLower();
await SetDefaultImage(context);
if (contentType.StartsWith("image"))
{
await SetDefaultImage(context);
}
}
}
/// <summary>
/// Return to the default picture
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
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);
await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
await context.Response.WriteAsync(ex.Message);
}
}
}
Be careful : Custom middleware classes must have constructors and Invoke Method , The former is to accept the next middleware Commission ; The latter is part of your middleware business implementation ;
4. stay Startup.cs in Configure Register custom middleware
public class Startup
{
/// requires using Microsoft.Extensions.Configuration;
private readonly IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseStaticFiles();
string url = Configuration["defaultImagePath"];
app.UseMiddleware<DefaultImageMiddleware>(url);// Register the middleware that returns the default picture
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
5. stay appsettings.json Add the relevant configuration
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"defaultImagePath": "wwwroot\\default.jpg"// Default tile image path
}
This is asking for pictures 404 when , You can return to the specified default picture
版权声明
本文为[Pingshan CP3]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220627116880.html
边栏推荐
- Web Course Design - his system
- Comprehensive calculation of employee information
- Huawei mobile ADB devices connection device is empty
- C WPF UI framework mahapps switching theme
- How does Microsoft solve the problem of multiple programs on PC side -- internal implementation
- Node configuration environment CMD does not take effect
- 2022T电梯修理考试模拟100题及在线模拟考试
- Fight leetcode again (290. Word law)
- C语言实现通讯录----(静态版本)
- socket編程 send()與 recv()函數詳解
猜你喜欢
一文了解全面静态代码分析
C WPF UI framework mahapps switching theme
[MySQL] left Function | Right Function
2022 P cylinder filling training test questions and simulation test
Yes Redis using distributed cache in NE6 webapi
xutils3修改了我提报的一个bug,开心
A comprehensive understanding of static code analysis
MySQL port is occupied when building xampp
Super easy to use [general excel import function]
Use of slice grammar sugar in C #
随机推荐
ThreadLocal test multithreaded variable instance
2022g2 boiler stoker examination question bank and online simulation examination
Fight leetcode again (290. Word law)
2022年做跨境电商五大技巧小分享
The most easy to understand dependency injection and control inversion
Detailed explanation of socket programming send() and recv() functions
The most understandable life cycle of dependency injection
. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
12.<tag-链表和常考点综合>-lt.234-回文链表
[mock data] fastmock dynamically returns the mock content according to the incoming parameters
Huawei mobile ADB devices connection device is empty
It can receive multiple data type parameters - variable parameters
2022a special equipment related management (elevator) work license question bank and simulation examination
ASP. Net 6 middleware series - execution sequence
The website JS in. Net core cefsharp chromium WebBrowser calls the C method in winfrom program
数据库表中不建索引,在插入数据时,通过sql语句防止重复添加(转载)
MySQL之explain关键字详解
Docker拉取mysql并连接
2022T电梯修理考试模拟100题及在线模拟考试
Log4net is in Net core usage