1016-.net core6.0 webapi 后端项目框架源码
【实例简介】
.net core 6.0 webapi Resful风格; 采用仓储 服务 接口的形式封装框架; 基于AOP切面的Redis缓存; 使用 Swagger 做api文档; 使用 Automapper 处理对象映射; 使用 AutoFac 做依赖注入容器,并提供批量服务注入; 支持 CORS 跨域; 封装 JWT 自定义策略授权; 接入国产数据库ORM组件 —— SqlSugar,封装数据库操作; 基于log4net的全局异常处理; 自定义全局消息返回格式; 可配合 Docker 实现容器化; 可配合 Jenkins 实现CI / CD; 可配合 Nginx 实现负载均衡;
【实例截图】
【核心代码】
var builder = WebApplication.CreateBuilder(args);
var ApiName = "Mag.Core.API";
//数据库配置
BaseDBConfig.ConnectionString = builder.Configuration.GetSection("AppSettings:ConnectionString").Value;
// Add services to the container.
builder.Services.AddControllers(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
options.Filters.Add(typeof(GlobalExceptionsFilter));
options.Filters.Add(typeof(AppResultFilter));
})
.AddNewtonsoftJson(options =>
{
//忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//不使用驼峰样式的key
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//设置时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//忽略Model中为null的属性
//options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
//设置本地时间而非UTC时间
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
})
.ConfigureApiBehaviorOptions(options => options.SuppressModelStateInvalidFilter = true);
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//注册appsettings读取类
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
//log日志注入
builder.Services.AddSingleton
//跨域服务配置
builder.Services.AddCors(options =>
{
options.AddPolicy("Cors", p =>
{
p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});
//注册swagger
builder.Services.AddSwaggerSetup();
//JWT安全验证
builder.Services.AddAuthorizationSetup();
//注册Redis
builder.Services.AddSingleton
//注入Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer
{
//调用程序集注册存入方法
builder.RegisterModule(new AutofacModuleRegister());
});
//注入AutoMapper
builder.Services.AddAutoMapper(typeof(CustomProfile));
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
//}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"/swagger/V1/swagger.json", $"{ApiName} V1");
//路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉,如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "doc";
c.RoutePrefix = "";
});
app.UseCors("Cors");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();