1.集成log4net
安装如下扩展依赖即可,已经包含了log4net依赖:
Microsoft.Extensions.Logging.Log4Net.AspNetCore
添加日志配置文件:
日志配置文件属性设置为始终复制:
注入服务:
#region 注入log4net日志服务
builder.Logging.AddLog4Net("Config/log4net.config");
#endregion
此时集成完毕。
2.集成automapper
安装如下依赖,此版本已经合并扩展依赖。
AutoMapper
编写配置映射类:
代码如下:
using AutoMapper;
using DataApi.Model.Dto;
using DataApi.Model.Entity;
namespace DataApi.Extension
{
/// <summary>
/// 映射描述类
/// </summary>
public class AutoMapperProfile : Profile
{
/// <summary>
/// 构造函数
/// </summary>
public AutoMapperProfile()
{
//部门
CreateMap<SysDept, SysDeptDto>();
}
}
}
注册服务:
#region 注入AutoMapper服务
builder.Services.AddAutoMapper(typeof(AutoMapperProfile));
#endregion
使用过程如下:
[HttpGet]
[Route("list")]
public async Task<ApiResult> GetSysDepts()
{
List<SysDept> sysDepts = await _sysDeptRepository.GetListAsync(opt => opt.DeptId == 100);
return ApiResult.Success(_mapper.Map<List<SysDeptDto>>(sysDepts));
}
对应的实体类和dto如下:
3.响应json时间本地化
安装如下依赖:
Microsoft.AspNetCore.Mvc.NewtonsoftJson
更改响应时间格式:
#region 更改响应时间格式
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
//更改响应时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
#endregion
4.集成跨域
注入服务:
#region 注入跨域服务
builder.Services.AddCors(options =>
{
options.AddPolicy("Cors", policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
#endregion
添加跨域中间件:
# region 跨域中间件
app.UseCors("Cors");
#endregion
5.集成sqlsugar
安装如下依赖:
SqlSugarCore
创建仓储:
using SqlSugar;
namespace DataApi.Repository
{
/// <summary>
/// 仓储类
/// </summary>
/// <typeparam name="T">T</typeparam>
public class Repository<T> : SimpleClient<T> where T : class, new()
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="db">ISqlSugarClient</param>
public Repository(ISqlSugarClient db)
{
base.Context = db;
}
}
}
执行扩展方法:
#region 注入Sqlsugar服务
builder.Services.AddSqlSugarExt("MySql");
#endregion
#region 注入泛型仓储
builder.Services.AddScoped(typeof(Repository<>));
#endregion
编写扩展类:
using DataApi.Common;
using SqlSugar;
using System.Data;
namespace DataApi.Extension
{
/// <summary>
/// SqlSugar扩展类
/// </summary>
public static class SqlSugarExt
{
/// <summary>
/// 扩展方法
/// </summary>
/// <param name="services">容器</param>
/// <param name="sqlType">数据库类型</param>
public static void AddSqlSugarExt(this IServiceCollection services, string sqlType = "MySql")
{
//注册SqlSugar
services.AddSingleton<ISqlSugarClient>(s =>
{
//配置实例
var configuration = s.GetRequiredService<IConfiguration>();
//日志实例
var logger = s.GetRequiredService<ILogger<Program>>();
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig
{
//数据库类型
DbType = ToolHelper.GetDbType(sqlType),
//连接字符串
ConnectionString = configuration.GetConnectionString(sqlType),
//自动关闭连接
IsAutoCloseConnection = true
},
db =>
{
//单例参数配置,所有上下文生效
db.Aop.OnLogExecuting = (sql, pars) =>
{
//输出sql
logger.LogInformation(sql);
if (pars != null)
{
//输出参数
logger.LogInformation(string.Join(",", pars.Select(p => p.ParameterName + ":" + p.Value)));
}
};
});
return sqlSugar;
});
}
}
}
获取dbtype:
using SqlSugar;
namespace DataApi.Common
{
/// <summary>
/// 工具帮助类
/// </summary>
public class ToolHelper
{
/// <summary>
/// GetDbType
/// </summary>
/// <param name="sqlType">string</param>
/// <returns>DbType</returns>
public static DbType GetDbType(string sqlType)
{
DbType dbType = DbType.MySql;
switch (sqlType)
{
case "SqlServer":
dbType = DbType.SqlServer;
break;
case "MySql":
dbType = DbType.MySql;
break;
case "Dm":
dbType = DbType.Dm;
break;
case "Oracle":
dbType = DbType.Oracle;
break;
case "PostgreSQL":
dbType = DbType.PostgreSQL;
break;
case "Sqlite":
dbType = DbType.Sqlite;
break;
}
return dbType;
}
}
}
跟datalink保持一致,只支持6种数据库。
6.jwt及swagger完整配置
安装如下依赖:
Microsoft.AspNetCore.Authentication.JwtBearer
Swashbuckle.AspNetCore.Filters
编写API版本类:
namespace DataApi.Common
{
/// <summary>
/// Api版本枚举
/// </summary>
public enum ApiVersion
{
/// <summary>
/// V1版本
/// </summary>
V1 = 1,
/// <summary>
/// V2版本
/// </summary>
V2
}
}
jwt配置类编写如下:
namespace DataApi.Common
{
/// <summary>
/// Jwt配置
/// </summary>
public class JwtSetting
{
/// <summary>
/// 密钥
/// </summary>
public string SecurityKey { get; set; } = string.Empty;
/// <summary>
/// 签发者
/// </summary>
public string? Issuer { get; set; }
/// <summary>
/// 签收者
/// </summary>
public string? Audience { get; set; }
/// <summary>
/// 过期时间
/// </summary>
public int ExpiredTime { get; set; }
}
}
appsettings.json配置内容如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
//MySql
"MySql": "Server=127.0.0.1;Database=dmp;Port=3306;Uid=root;Pwd=wong123456;Allow User Variables=True;",
//SqlServer
"SqlServer": "Data Source=43.143.48.100;Initial Catalog=ALEAN;User Id=sa;Password=ghy520WXF;"
},
//Jwt配置
"JwtSetting": {
//密钥
"SecurityKey": "7k5yOxSMHVdYjs61gkgUY3W9DHbgk7tokaZlP3QIlfk34D1H7jYEOcLybClW1aKl",
//签发者
"Issuer": "DataApi",
//签收者
"Audience": "DataApi",
//过期时间,单位秒,默认24小时
"ExpiredTime": 86400
}
}
注入配置:
#region 注入Jwt服务
builder.AddJwtExt();
#endregion
#region 注入Swagger服务
builder.AddSwaggerExt();
#endregion
#region 注入Jwt配置
builder.Services.Configure<JwtSetting>(builder.Configuration.GetSection("JwtSetting"));
#endregion
# region SwaggerUI配置
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
app.UseSwaggerExt();
}
#endregion
# region 认证中间件
app.UseAuthentication();
#endregion
jwtAuth扩展:
using DataApi.Common;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace DataApi.Extension
{
/// <summary>
/// Jwt扩展类
/// </summary>
public static class JwtAuthExt
{
/// <summary>
/// 扩展方法
/// </summary>
/// <param name="builder">WebApplicationBuilder</param>
public static void AddJwtExt(this WebApplicationBuilder builder)
{
#region 注入认证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
JwtSetting jwtSetting = builder.Configuration.GetSection("JwtSetting").Get<JwtSetting>();
options.TokenValidationParameters = new TokenValidationParameters()
{
//是否验证Issuer
ValidateIssuer = true,
ValidIssuer = jwtSetting.Issuer,
//是否验证Audience
ValidateAudience = true,
ValidAudience = jwtSetting.Audience,
//是否验证失效时间
ValidateLifetime = true, //默认含300s容错时间
//是否验证SecurityKey
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.SecurityKey))
};
});
#endregion
}
}
}
swagger扩展:
using DataApi.Common;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using System.Reflection;
using System.Text;
namespace DataApi.Extension
{
/// <summary>
/// Swagger扩展类
/// </summary>
public static class SwaggerExt
{
/// <summary>
/// 扩展方法
/// </summary>
/// <param name="builder">WebApplicationBuilder</param>
public static void AddSwaggerExt(this WebApplicationBuilder builder)
{
builder.Services.AddSwaggerGen(options =>
{
//遍历所有版本,展示文档信息
typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
{
//添加文档介绍
options.SwaggerDoc(version, new OpenApiInfo()
{
Title = "DataApi",
Version = version,
Description = $"数据接口服务:【{version}】版本"
});
});
//获取xml文件名称
string xmlApiFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//显示控制器注释
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlApiFileName), true);
//根据action名称进行排序
options.OrderActionsBy(o => o.RelativePath);
//开启加权小锁
options.OperationFilter<AddResponseHeadersFilter>();
//options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
// 在header中添加token,传递到后台
//options.OperationFilter<SecurityRequirementsOperationFilter>();
//添加安全定义
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "在下框中输入Jwt授权Token:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
//添加安全要求
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme()
{
Reference = new OpenApiReference()
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
}
});
options.SchemaFilter<DateTimeSchemaFilter>();
});
}
/// <summary>
/// 扩展方法
/// </summary>
/// <param name="app">WebApplication</param>
public static void UseSwaggerExt(this WebApplication app)
{
app.UseSwagger();
//版本切换
app.UseSwaggerUI(options =>
{
typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
{
options.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"【{version}】版本");
});
});
}
}
}
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace DataApi.Extension
{
/// <summary>
/// DateTimeSchemaFilter
/// </summary>
public class DateTimeSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (context.Type == typeof(DateTime) || context.Type == typeof(DateTime?))
{
schema.Default = new OpenApiString(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //设置为当前时间
}
}
}
}
7.响应结果封装
using Newtonsoft.Json;
using System.Net;
namespace DataApi.Common
{
/// <summary>
/// 封装响应数据
/// </summary>
public class ApiResult
{
/// <summary>
/// 状态码
/// </summary>
public HttpStatusCode Code { get; set; }
/// <summary>
/// 消息
/// </summary>
public string? Message { get; set; }
/// <summary>
/// 数据
/// </summary>
public object? Data { get; set; }
/// <summary>
/// 无参构造函数
/// </summary>
public ApiResult()
{
}
/// <summary>
/// 带参构造函数
/// </summary>
/// <param name="code">状态码</param>
/// <param name="message">消息</param>
/// <param name="data">数据</param>
public ApiResult(HttpStatusCode code, string message, object data)
{
Code = code;
Message = message;
Data = data;
}
/// <summary>
/// 序列化对象
/// </summary>
/// <returns>json字符串</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
/// <summary>
/// Success标志
/// </summary>
/// <param name="data">数据</param>
/// <returns>ApiResult</returns>
public static ApiResult Success(object data)
{
return new ApiResult(HttpStatusCode.OK, "操作成功", data);
}
/// <summary>
/// Error标志
/// </summary>
/// <param name="message">消息</param>
/// <returns>ApiResult</returns>
public static ApiResult Error(string message)
{
return new ApiResult(HttpStatusCode.OK, message, "Error");
}
/// <summary>
/// Unauthorized标志
/// </summary>
/// <returns>ApiResult</returns>
public static ApiResult Unauthorized()
{
return new ApiResult(HttpStatusCode.Unauthorized, "Unauthorized", "Unauthorized");
}
/// <summary>
/// Forbidden标志
/// </summary>
/// <returns>ApiResult</returns>
public static ApiResult Forbidden()
{
return new ApiResult(HttpStatusCode.Forbidden, "Forbidden", "Forbidden");
}
}
}