.net core 自动注入。。。。懵逼。。
using Microsoft.AspNetCore.Http; using System.Globalization; using System.Threading.Tasks; namespace Culture { public class tets { //调用我的自定义类 public void eee() { HttpContext context = null; RequestDelegate requestDelegate = myfun; RequestCultureMiddleware requestCultureMiddleware = new RequestCultureMiddleware(requestDelegate); //构造方法传递一个委托 requestCultureMiddleware.Invoke(context); } public async Task myfun(HttpContext context) { } }
//自定义类 public class RequestCultureMiddleware { private readonly RequestDelegate _next; // 定义一个委托 public RequestCultureMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context) { //每次请求 都会 执行 var cultureQuery = context.Request.Query["culture"]; if (!string.IsNullOrWhiteSpace(cultureQuery)) { var culture = new CultureInfo(cultureQuery); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; } //调用管道中的下一个委托 / 中间件 return this._next(context); } } }
//自动调用
public static class RequestCultureMiddlewareExtensions { public static IApplicationBuilder UseRequestCulture(this IApplicationBuilder builder) { //调用该方法传递一个类 ;添加一个中间件类型应用程序的请求管道 // 其中 RequestCultureMiddleware 是 自定义类 //执行该方法 会自动注入 该类中所需要的对象 RequestDelegate next return builder.UseMiddleware<RequestCultureMiddleware>(); } }
app.UseRequestCulture(); //调用中间件 执行 后, 每次都会调用 Invoke 函数
转自 : https://cloud.tencent.com/developer/article/1151209