【.Net】【C#】Web Core Api 通用代码模板
- 常用NuGet
- Program.cs
- appsettings.json
- log4net.config
- [VS2022 swagger文档配置](#VS2022 swagger文档配置)
常用NuGet
Microsoft.Extensions.Logging.Log4Net.AspNetCore
Flurl
Flurl.Http
Program.cs
c#
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.SwaggerUI;
namespace model
{
/// <summary>
///
/// </summary>
public class Program
{
public static void Main(string[] args)
{
#region 自定义配置
var builder = WebApplication.CreateBuilder(args);
builder
.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//配置返回Json大小写格式与Model一致
//options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//统一设置日期格式
//options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
});
builder.Services.AddControllers();
//添加全局异常处理机制
builder.Services.AddMvc(option =>
{
option.Filters.Add<ExceptionHandler>();
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc(
"v1",
new OpenApiInfo
{
Version = "v1",
Title = AppSettingsHelper.GetSetting("AppName"),
Description = $"API描述,v1版本",
}
);
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//IncludeXmlComments 第二参数 true 则显示 控制器 注释
options.IncludeXmlComments(
Path.Combine(AppContext.BaseDirectory, xmlFilename),
true
);
#region 启用swagger验证功能
options.AddSecurityDefinition(
"Authorization",
new OpenApiSecurityScheme()
{
Description = "在下框中输入请求头中需要添加授权token:Authorization",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "Authorization",
Scheme = "Authorization",
}
);
options.AddSecurityRequirement(
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Authorization",
},
},
Array.Empty<string>()
},
}
);
#endregion
});
//校验配置
builder
.Services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
//options.SuppressConsumesConstraintForFormFileParameters = true;
//options.SuppressInferBindingSourcesForParameters = true;
options.SuppressModelStateInvalidFilter = true;
options.SuppressMapClientErrors = true;
options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "/error";
});
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(m => m.DocExpansion(DocExpansion.None));
//app.UseHttpsRedirection();
//跨域
//app.UseCors("Cors");
// 设置允许所有来源跨域
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.SetPreflightMaxAge(TimeSpan.FromSeconds(2000000));
});
//app.UseAuthentication();
//app.UseAuthorization();
app.MapControllers();
#region 配置中心刷新配置
//new ConnStr();
#endregion
app.Run();
#endregion
}
}
/// <summary>
/// 异常拦截器
/// </summary>
public class ExceptionHandler : IExceptionFilter
{
/// <summary>
/// 异常拦截器
/// </summary>
/// <param name="context"></param>
public void OnException(ExceptionContext context)
{
if (!context.ExceptionHandled) //如果异常没有被处理过
{
Exception ex = context.Exception;
//Logger.Log(ex.ToString(), Level.ERROR);
var request = context.HttpContext.Request;
string url = request.Path + context.HttpContext.Request.QueryString;
//var ParamPost = JsonConvert.SerializeObject(request.Method == "POST" ? request.Form : "");
//Logger.Log($"url={url},param={ParamPost}");
//全局错误返回
//context.Result = new JsonResult(ResponseUtil.Error(ex.Message))
//{
// StatusCode = (int)HttpStatusCode.OK
//};
Logger.Log(
$"url={url},ex.Message={ex.Message},ex.StackTrace={ex.StackTrace}",
Level.ERROR
);
//全局错误返回
context.Result = new OkObjectResult(ResponseModelInfo.SysError(ex.ToString()));
context.ExceptionHandled = true;
}
}
}
}
appsettings.json
json
{
"AppName": "样例",
"Kestrel": {
"Endpoints": {
"Http": { "Url": "http://*:9000/" }
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
log4net.config
xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<appender name="RollingLogFileAppender"
type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="logs\" />
<datePattern value="'info-'yyyy-MM-dd'.log'"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="30MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern
value="%date [%thread][%-5level][%logger][%line] %message%newline"/>
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread][%-5level][%logger][%line] %message%newline" />
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="RollingLogFileAppender"/>
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
</configuration>