This commit is contained in:
qianhao.xu
2025-02-21 13:04:44 +08:00
parent f80aca492c
commit 218a1ce86a
8 changed files with 191 additions and 95 deletions

View File

@@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DOAN.ServiceCore.Middleware
{
public class UtcToLocalMiddleware
{
private readonly RequestDelegate _next;
public UtcToLocalMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 检查是否是GET请求
if (HttpMethods.IsGet(context.Request.Method))
{
var query = context.Request.Query; // 获取查询参数集合
var queryParams = new List<KeyValuePair<string, StringValues>>();
foreach (var queryParameter in query)
{
if(queryParameter.Value.Count()>0)
{
foreach (var value in queryParameter.Value)
{
if (DateTime.TryParse(value,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out DateTime utcDate))
{
// 转换为本地时间
var localTime = utcDate.ToLocalTime();
queryParams.Add(new KeyValuePair<string, StringValues>(queryParameter.Key, new StringValues(localTime.ToString("o"))));
}
else
{
// 如果不是时间格式,则保持原样添加
queryParams.Add(new KeyValuePair<string, StringValues>(queryParameter.Key, new StringValues(value)));
}
}
}
}
// 构建新的 QueryString
var newQueryString = string.Join("&", queryParams.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value)}"));
context.Request.QueryString = new QueryString("?" + newQueryString);
}
// Call the next delegate/middleware in the pipeline
await _next(context);
}
}
}

View File

@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Globalization;
using System.Threading.Tasks;
public class LocalDateModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == ValueProviderResult.None)
return Task.CompletedTask;
var dateStr = valueProviderResult.FirstValue;
// 尝试根据特定格式和当前文化信息解析日期字符串
if (DateTime.TryParse(dateStr, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out DateTime parsedDate))
{
bindingContext.Result = ModelBindingResult.Success(parsedDate);
}
else
{
bindingContext.ModelState.TryAddModelError(
bindingContext.ModelName,
"Invalid date format.");
}
return Task.CompletedTask;
}
}

View File

@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
public class LocalDateModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(DateTime))
{
return new LocalDateModelBinder();
}
return null;
}
}