入口方法,异常拦截器,返回jsonkey大写,跨域,summary注释变API说明
打开项目的.csproj文件加上 添加
<GenerateDocumentationFile>true</GenerateDocumentationFile>
/// <summary>
/// 入口
/// </summary>
public static void Main(string[] args)
{
#region 自定义配置
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
//设置JSON返回key格式大写
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.AddControllers();
//添加全局异常处理机制
builder.Services.AddMvc(option =>
{
option.Filters.Add<ExceptionHandler>();
});
//配置跨域
/*builder.Services.AddCors(cor =>
{
var cors = AppSettingsHelper.GetSetting("AllowCorsUrls")?.Split(',');
cor.AddPolicy("Cors", policy =>
{
policy.WithOrigins(cors)//设置允许的请求头
.WithExposedHeaders("x-custom-header")//设置公开的响应头
.AllowAnyHeader()//允许所有请求头
.AllowAnyMethod()//允许任何方法
.AllowCredentials()//允许跨源凭据----服务器必须允许凭据
.SetIsOriginAllowed(_ => true);
});
});*/
// 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 = "API标题",
Description = $"API描述,v1版本"
});
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//IncludeXmlComments 第二参数 true 则显示 控制器 注释
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
// app.UseSwagger();
// app.UseSwaggerUI();
//}
app.UseSwagger();
app.UseSwaggerUI();
//app.UseHttpsRedirection();
//跨域
app.UseCors("Cors");
app.UseAuthorization();
app.MapControllers();
app.Run();
#endregion
}
}
/// <summary>
/// 异常拦截器
/// </summary>
public class ExceptionHandler : IExceptionFilter
{
/// <summary>
/// 异常拦截器
/// </summary>
/// <param name="context"></param>
public void OnException(ExceptionContext context)
{
if (!context.ExceptionHandled)//如果异常没有被处理过
{
Exception e = context.Exception;
Logger.Log(e.ToString(), Level.ERROR);
}
}
}
【跨域配置】appsettings.json根节点添加配置
"Kestrel": {
"Endpoints": {
"Http": { "Url": "http://*:5072/" }
}
},
接口写法
/// <summary>
/// controller示例
/// </summary>
[ApiController]
[Route("[controller]")]
public class DemoController : Controller
{
/// <summary>
/// 接口示例
/// </summary>
/// <param name="param">参数</param>
/// <returns></returns>
[HttpGet]
[Route("[action]")]
public object Test(int param= 1)
{
return null;
}
}