You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

190 lines
8.9 KiB
C#

using System.Diagnostics;
10 months ago
using System.Text;
using System.Web;
10 months ago
using DS.Module.Core;
using DS.Module.Core.Extensions;
using DS.Module.Core.Log;
10 months ago
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
10 months ago
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
10 months ago
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetTaste;
10 months ago
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
10 months ago
using SqlSugar;
using Parser = UAParser.Parser;
10 months ago
namespace DS.Module.MultiLanguage;
/// <summary>
/// 多语言中间件
/// </summary>
public class MultiLanguageMiddleware
{
private readonly RequestDelegate _next;
public IMultiLanguageService _invokeService;
private readonly IServiceProvider _serviceProvider;
private readonly SqlSugarScope db;
private Stopwatch _stopwatch;
10 months ago
public MultiLanguageMiddleware(RequestDelegate next, IServiceProvider serviceProvider)
{
_next = next;
_stopwatch = new Stopwatch();
10 months ago
_serviceProvider = serviceProvider;
_invokeService = _serviceProvider.GetRequiredService<IMultiLanguageService>();
// db = (SqlSugarScope)_serviceProvider.GetRequiredService<ISqlSugarClient>();
10 months ago
}
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();
10 months ago
using (var ms = new MemoryStream())
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
10 months ago
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<DataResult>(responseBodyText);
var serializerSettings = new JsonSerializerSettings
{
// 设置为驼峰命名
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
if (msg.IsNotEmptyOrNull())
10 months ago
{
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);
}
}
10 months ago
}
// 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<IEndpointFeature>()?.Endpoint;
// if (endpoint is RouteEndpoint routeEndpoint)
// {
// controllerName = routeEndpoint.Metadata.GetMetadata<ControllerActionDescriptor>()?.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();
// }
10 months ago
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);
}
}
}
}
10 months ago
}