Files
tnb.server/apihost/Tnb.API.Entry/Extensions/ConfigureMvcControllerExtensions.cs
2023-03-28 15:29:09 +08:00

77 lines
2.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using JNPF;
using JNPF.Common.Core.Filter;
using JNPF.Common.Options;
using JNPF.EventHandler;
using JNPF.JsonSerialization;
using JNPF.UnifyResult;
using Microsoft.AspNetCore.HttpOverrides;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using OnceMi.AspNetCore.OSS;
using JNPF.API.Entry.Handlers;
using JNPF.Common.Cache;
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)
{
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());
});
// 配置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);
// 跨域
services.AddCorsAccessor();
services.AddConfigurableOptions<CacheOptions>();
services.AddSession();
services.AddMemoryCache(); // 使用本地缓存必须添加
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
return services;
}
}