当前位置:网站首页>. 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
边栏推荐
- Do you really understand hashcode and equals???
- Seminar playback video: how to improve Jenkins' ability to become a real Devops platform
- . net core current limiting control - aspnetcoreratelimit
- 2022 Shandong Province safety officer C certificate work certificate question bank and online simulation examination
- C syntax pattern matching [switch expression]
- Improvement of ref and struct in C 11
- socket編程 send()與 recv()函數詳解
- Student achievement management
- 2022 P cylinder filling training test questions and simulation test
- Source generator actual combat
猜你喜欢

12. < tag linked list and common test site synthesis > - lt.234 palindrome linked list

手机连接电脑后,QT的QDIR怎么读取手机文件路径

类似Jira的十大项目管理软件

Huawei mobile ADB devices connection device is empty

MySQL port is occupied when building xampp

MySQL之explain关键字详解

New ORM framework -- Introduction to beetlsql

Ide-idea-problem

软件测试相关知识~

【无标题】
随机推荐
Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
可以接收多种数据类型参数——可变参数
Yes Redis using distributed cache in NE6 webapi
js递归树结构计算每个节点的叶子节点的数量并且输出
First in the binary tree
数据挖掘系列(3)_Excel的数据挖掘插件_估计分析
12. < tag linked list and common test site synthesis > - lt.234 palindrome linked list
Do you really understand hashcode and equals???
ASP. Net 6 middleware series - Custom middleware classes
2022t elevator repair test simulation 100 questions and online simulation test
软件测试相关知识~
场景题:A系统如何使用B系统的页面
Test experience data
Swap the left and right of each node in a binary tree
POI create and export Excel based on data
Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types
C language to achieve address book - (static version)
Chapter 8 of C language programming (fifth edition of Tan Haoqiang) is good at using pointer exercises to analyze and answer
After the mobile phone is connected to the computer, how can QT's QDIR read the mobile phone file path
[mock data] fastmock dynamically returns the mock content according to the incoming parameters