163 lines
6.3 KiB
C#
163 lines
6.3 KiB
C#
using System.Globalization;
|
||
using JNPF.API.Entry.Handlers;
|
||
using JNPF.Common.Core.Filter;
|
||
using JNPF.JsonSerialization;
|
||
using JNPF.UnifyResult;
|
||
using Mapster;
|
||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||
using Microsoft.AspNetCore.HttpOverrides;
|
||
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Serialization;
|
||
using Tnb.Vengine;
|
||
|
||
namespace Microsoft.Extensions.DependencyInjection;
|
||
|
||
/// <summary>
|
||
/// OSS服务配置拓展.
|
||
/// </summary>
|
||
public static class ConfigureMvcControllerExtensions
|
||
{
|
||
/// <summary>
|
||
/// OSS服务配置.
|
||
/// </summary>
|
||
/// <param name="services"></param>
|
||
/// <returns></returns>
|
||
public static IServiceCollection ConfigureMvcController(this IServiceCollection services)
|
||
{
|
||
AdapterCfg.ConfigGlobal();
|
||
services.AddControllers()
|
||
.AddMvcFilter<RequestActionFilter>()
|
||
.AddInjectWithUnifyResult<RESTfulResultProvider>()
|
||
.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null)
|
||
.AddNewtonsoftJson(options =>
|
||
{
|
||
// 默认命名规则
|
||
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
|
||
|
||
// 设置时区为 UTC
|
||
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
|
||
|
||
// 格式化json输出的日期格式
|
||
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
|
||
|
||
// 忽略空值
|
||
// options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
|
||
|
||
// 忽略循环引用
|
||
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
||
|
||
// 格式化json输出的日期格式为时间戳
|
||
// options.SerializerSettings.Converters.Add(new NewtonsoftDateTimeJsonConverter());
|
||
options.SerializerSettings.Converters.Add(new MyNewtonsoftDateTimeJsonConverter());//zhoukeda 2023.10.24
|
||
});
|
||
|
||
services.AddUnifyJsonOptions("special", new JsonSerializerSettings
|
||
{
|
||
// 默认命名规则
|
||
ContractResolver = new DefaultContractResolver(),
|
||
|
||
// 设置时区为 UTC
|
||
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
|
||
|
||
// 格式化json输出的日期格式
|
||
DateFormatString = "yyyy-MM-dd HH:mm:ss",
|
||
});
|
||
|
||
// 配置Nginx转发获取客户端真实IP
|
||
// 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear()
|
||
// 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码
|
||
services.Configure<ForwardedHeadersOptions>(options =>
|
||
{
|
||
options.ForwardedHeaders = ForwardedHeaders.All;
|
||
options.KnownNetworks.Clear();
|
||
options.KnownProxies.Clear();
|
||
});
|
||
|
||
// Jwt处理程序
|
||
services.AddJwt<JwtHandler>(enableGlobalAuthorize: true, jwtBearerConfigure: options =>
|
||
{
|
||
// 实现 JWT 身份验证过程控制
|
||
options.Events = new JwtBearerEvents
|
||
{
|
||
// 添加读取 Token 的方式
|
||
OnMessageReceived = context =>
|
||
{
|
||
var httpContext = context.HttpContext;
|
||
|
||
// 判断请求是否包含 token 参数,如果有就设置给 Token
|
||
if (httpContext.Request.Query.ContainsKey("token"))
|
||
{
|
||
// 设置 Token
|
||
context.Token = httpContext.Request.Query["token"];
|
||
}
|
||
|
||
return Task.CompletedTask;
|
||
},
|
||
|
||
// Token 验证通过处理
|
||
OnTokenValidated = context =>
|
||
{
|
||
return Task.CompletedTask;
|
||
},
|
||
};
|
||
});
|
||
|
||
// 跨域
|
||
services.AddCorsAccessor();
|
||
|
||
// 注册远程请求
|
||
services.AddRemoteRequest();
|
||
|
||
// 视图引擎
|
||
services.AddViewEngine();
|
||
|
||
// 脱敏词汇检测
|
||
services.AddSensitiveDetection();
|
||
|
||
// WebSocket服务
|
||
services.AddWebSocketManager();
|
||
|
||
services.AddSession();
|
||
|
||
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||
|
||
return services;
|
||
}
|
||
|
||
public class MyNewtonsoftDateTimeJsonConverter : NewtonsoftDateTimeJsonConverter
|
||
{
|
||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||
{
|
||
bool flag = NewtonsoftDateTimeJsonConverter.IsNullable(objectType);
|
||
if (reader.TokenType == JsonToken.Null || string.IsNullOrEmpty(reader.Value.ToString()))
|
||
{
|
||
if (!flag)
|
||
throw new JsonSerializationException(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Cannot convert null value to {0}.", (object)objectType));
|
||
return (object)null;
|
||
}
|
||
long result = 0;
|
||
if (reader.TokenType == JsonToken.Integer)
|
||
result = (long)reader.Value;
|
||
else if (reader.TokenType == JsonToken.String)
|
||
{
|
||
if (!long.TryParse((string)reader.Value, out result))
|
||
return (object)Convert.ToDateTime(reader.Value.ToString());
|
||
return reader.TokenType == JsonToken.Date ? reader.Value : throw new JsonSerializationException(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unexpected token parsing date. Expected Integer or String, got {0}.", (object)reader.TokenType));
|
||
}
|
||
if (result < 0L)
|
||
return (object)DateTime.Now;
|
||
try
|
||
{
|
||
DateTime dt = Convert.ToDateTime(reader.Value.ToString());
|
||
return dt;
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(result);
|
||
dateTimeOffset = dateTimeOffset.ToLocalTime();
|
||
DateTime dateTime = dateTimeOffset.DateTime;
|
||
return (flag ? Nullable.GetUnderlyingType(objectType) : objectType) == typeof(DateTimeOffset) ? (object)new DateTimeOffset(dateTime, TimeSpan.Zero) : (object)dateTime;
|
||
}
|
||
}
|
||
}
|
||
} |