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.

85 lines
3.1 KiB
C#

10 months ago
using System.Text;
using DS.Module.Core;
using DS.Module.Core.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using SqlSugar;
namespace DS.Module.MultiLanguage;
/// <summary>
/// 多语言中间件
/// </summary>
public class MultiLanguageMiddleware
{
private readonly RequestDelegate _next;
public IMultiLanguageService _invokeService;
private readonly IServiceProvider _serviceProvider;
private readonly SqlSugarScope db;
public MultiLanguageMiddleware(RequestDelegate next, IServiceProvider serviceProvider)
{
_next = next;
_serviceProvider = serviceProvider;
_invokeService = _serviceProvider.GetRequiredService<IMultiLanguageService>();
}
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"))
{
using (var ms = new MemoryStream())
{
HttpResponse response = context.Response;
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 type = context.Request.Headers["LanguageType"].FirstOrDefault();
if (type.IsNullOrEmpty())
{
type = "CN";
}
//多语言处理返回信息
var langugaeSet = _invokeService.GetMultiLanguageInfo(msg.MultiCode, type);
if (!langugaeSet.IsNullOrEmpty())
{
msg.Message = langugaeSet;
responseBodyText = JsonConvert.SerializeObject(msg);
}
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);
}
}
}
}
}