当前位置:网站首页>. 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
边栏推荐
- Advanced sorting - fast sorting
- 软件测试相关知识~
- 12. < tag linked list and common test site synthesis > - lt.234 palindrome linked list
- js递归树结构计算每个节点的叶子节点的数量并且输出
- Fiddler use
- . NETCORE sets the API post mode, which can accept parameters directly in parentheses
- socket編程 send()與 recv()函數詳解
- Yes Redis using distributed cache in NE6 webapi
- Flink实时数仓项目—DWS层设计与实现
- 《C语言程序设计》(谭浩强第五版) 第7章 用函数实现模块化程序设计 习题解析与答案
猜你喜欢

New ORM framework -- Introduction to beetlsql

Blazor University (12) - component lifecycle

Impact of AOT and single file release on program performance

How does Microsoft solve the problem of multiple PC programs

Student achievement management

2022 Shandong Province safety officer C certificate work certificate question bank and online simulation examination

一套组合拳,打造一款 IDEA 护眼方案

MySql关键字GROUP_CONCAT,组合连接查询

数据挖掘系列(3)_Excel的数据挖掘插件_估计分析

How does Microsoft solve the problem of multiple programs on PC side -- internal implementation
随机推荐
ASP. Net and ASP NETCORE multi environment configuration comparison
类似Jira的十大项目管理软件
Flink实时数仓项目—DWS层设计与实现
Knowledge of software testing~
ASP. Net 6 middleware series - Custom middleware classes
2022 Shandong Province safety officer C certificate work certificate question bank and online simulation examination
. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
Student achievement management
yes. Net future
OLED多级菜单记录
Top ten project management software similar to JIRA
Scenario Title: how does system a use the page of system B
Cefsharp stores cookies and reads cookies
socket编程 send()与 recv()函数详解
Mysql database design specification
Flink real-time data warehouse project - Design and implementation of DWS layer
Charles uses three ways to modify requests and responses
How does Microsoft solve the problem of multiple PC programs
一套组合拳,打造一款 IDEA 护眼方案
Docker拉取mysql并连接