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.

79 lines
3.3 KiB
C#

12 months ago
using DS.Module.Core;
using DS.Module.Core.Filters;
using DS.Module.Core.Helpers;
12 months ago
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
7 months ago
using Microsoft.Extensions.DependencyInjection;
12 months ago
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
12 months ago
7 months ago
namespace DS.Module.Core.ServiceExtensions;
12 months ago
/// <summary>
/// 基础服务
/// </summary>
public static class DsAppWebInstall
{
/// <summary>
/// 将模块服务添加到依赖注入服务容器中
/// </summary>
/// <param name="services">依赖注入服务容器</param>
/// <returns></returns>
public static IServiceCollection AddAppWebInstal(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
//注册http请求服务
services.AddHttpClient();
services.AddControllers(options =>
{
options.Filters.Add<ApiUserFilter>();
12 months ago
// 204预检查过滤
//options.Filters.Add<FegCrosFilter>();
//全局异常过滤
options.Filters.Add<GlobalExceptionsFilter>();
////全局操作日志
//options.Filters.Add<OperationLogFilter>();
7 months ago
12 months ago
options.SuppressAsyncSuffixInActionNames = false;
//关闭不可为空引用类型的属性
options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
12 months ago
})
.ConfigureApiBehaviorOptions(options =>
{
//SuppressModelStateInvalidFilter =true时会关闭默认模型验证过滤器。[ApiController] 默认自带有400模型验证且优先级比较高如果需要自定义模型验证则需要先关闭默认的模型验证。
options.SuppressModelStateInvalidFilter = false;
//使用自定义模型验证
options.InvalidModelStateResponseFactory = (context) =>
{
var errors = context.ModelState
.Where(e => e.Value.Errors.Count > 0)
.Select(e => e.Value.Errors.First().ErrorMessage)
.ToList();
7 months ago
var result = DataResult<object>.Failed(string.Join("|", errors));
12 months ago
return new JsonResult(result);
};
})
//全局配置Json序列化处理
.AddNewtonsoftJson(options =>
{
11 months ago
//CustomContractResolver 是我们自定义的解析器
options.SerializerSettings.ContractResolver = new CustomContractResolver();
// // 首字母小写(驼峰样式)
// options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
12 months ago
// 时间格式化
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
// 忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// 忽略空值
// options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
})
;
//添加FluentValidation验证
services.AddFluentValidationAutoValidation();
return services;
}
}