using System.Diagnostics; using System.Text; using System.Web; using DS.Module.Core; using DS.Module.Core.Extensions; using DS.Module.Core.Log; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetTaste; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SqlSugar; using Parser = UAParser.Parser; namespace DS.Module.MultiLanguage; /// /// 多语言中间件 /// public class MultiLanguageMiddleware { private readonly RequestDelegate _next; public IMultiLanguageService _invokeService; private readonly IServiceProvider _serviceProvider; private readonly SqlSugarScope db; private Stopwatch _stopwatch; public MultiLanguageMiddleware(RequestDelegate next, IServiceProvider serviceProvider) { _next = next; _stopwatch = new Stopwatch(); _serviceProvider = serviceProvider; _invokeService = _serviceProvider.GetRequiredService(); // db = (SqlSugarScope)_serviceProvider.GetRequiredService(); } public async Task Invoke(HttpContext context) { if (context.Request.Path.HasValue && ( context.Request.Path.Value.IndexOf("SignalR", StringComparison.InvariantCultureIgnoreCase) > -1 || context.Request.Path.Value.IndexOf("swagger", StringComparison.InvariantCultureIgnoreCase) > -1 || context.Request.Path.Value.IndexOf("HealthCheck", StringComparison.InvariantCultureIgnoreCase) > -1 ) ) { await _next(context); } else { var api = context.Request.Path.ObjToString().TrimEnd('/').ToLower(); // 过滤,只有接口 if (api.Contains("api")) { _stopwatch.Restart(); using (var ms = new MemoryStream()) { HttpResponse response = context.Response; HttpRequest request = context.Request; var originalResponseBody = response.Body; using var newResponseBody = new MemoryStream(); response.Body = newResponseBody; await _next(context); newResponseBody.Seek(0, SeekOrigin.Begin); var responseBodyText = await new StreamReader(response.Body).ReadToEndAsync(); var msg = JsonConvert.DeserializeObject(responseBodyText); var serializerSettings = new JsonSerializerSettings { // 设置为驼峰命名 ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; if (msg.IsNotEmptyOrNull()) { var type = context.Request.Headers["LanguageType"].FirstOrDefault(); if (type.IsNullOrEmpty()) { type = "CN"; } if (msg.MultiCode.IsNotEmptyOrNull()) { //多语言处理返回信息 var langugaeSet = _invokeService.GetMultiLanguageInfo(msg.MultiCode, type); if (!langugaeSet.IsNullOrEmpty()) { msg.Message = langugaeSet; responseBodyText = JsonConvert.SerializeObject(msg,Formatting.None, serializerSettings); } } } // if (AppSetting.app("Middleware", "RecordAccessLogs", "Enabled").ObjToBool()) // { // // var headers = request.Headers; // var clientInfo = headers.ContainsKey("User-Agent") // ? Parser.GetDefault().Parse(headers["User-Agent"]) // : null; // var controllerName = string.Empty; // var endpoint = context.Features.Get()?.Endpoint; // if (endpoint is RouteEndpoint routeEndpoint) // { // controllerName = routeEndpoint.Metadata.GetMetadata()?.ControllerName; // } // var log = new SysLogOperation() // { // // Name = context.User?.FindFirstValue(ClaimConst.CLAINM_NAME), // Ip = HttpUtil.GetClientIP(context), // Location = HttpUtil.GetRequestUrlAddress(request), // Browser = clientInfo?.UA.Family + clientInfo?.UA.Major, // Os = clientInfo?.OS.Family + clientInfo?.OS.Major, // Url = request.Path, // ClassName = controllerName, // MethodName = context.GetRouteData().Values["action"].ToString(), // ReqMethod = request.Method, // OpTime = DateTime.Now, // }; // // // 获取请求body内容 // if (request.Method.ToLower().Equals("post") || request.Method.ToLower().Equals("put")) // { // // 启用倒带功能,就可以让 Request.Body 可以再次读取 // request.EnableBuffering(); // byte[] buffer = new byte[request.ContentLength.Value]; // Stream stream = request.Body; // // await stream.ReadAsync(buffer, 0, buffer.Length); // // // // request.Body.Seek(0, SeekOrigin.Begin); // // using (var reader = new StreamReader(request.Body, Encoding.UTF8)) // // { // // //改为Async异步读流 // // var data = await reader.ReadToEndAsync(); // // log.Param = data; // // // var obj = JObject.Parse(log.Param) ; // // log.KeyId = data.IsNullOrEmpty() ? 0: JObject.Parse(data)?.GetLongValue("Id"); // // } // request.Body.Position = 0; // log.Param = Encoding.UTF8.GetString(buffer); // //TODO 待处理问题 KeyId // // var obj = JObject.Parse(log.Param) ; // // if (!log.Param.IsNullOrEmpty()) // // { // // log.KeyId = JObject.Parse(log.Param)?.GetLongValue("Id"); // // } // } // else if (request.Method.ToLower().Equals("get") || request.Method.ToLower().Equals("delete")) // { // log.Param = // HttpUtility.UrlDecode(request.QueryString.ObjToString(), Encoding.UTF8); // } // // _stopwatch.Stop(); // // if (context.Response.StatusCode == 200 && !context.Response.HasStarted) // { // log.Success = true; // } // else // { // log.Success = false; // } // // // log.Result = JsonConvert.SerializeObject(msg, Formatting.None, serializerSettings); // log.ElapsedTime = _stopwatch.ElapsedMilliseconds; // await db.GetConnection(1288018625843826680).Insertable(log).ExecuteCommandAsync(); // } byte[] array = Encoding.UTF8.GetBytes(responseBodyText); using var newBodyStream = new MemoryStream(array); newBodyStream.Seek(0, SeekOrigin.Begin); response.ContentLength = newBodyStream.Length; await newBodyStream.CopyToAsync(originalResponseBody); } } } } }