-
Notifications
You must be signed in to change notification settings - Fork 161
/
Program.cs
95 lines (82 loc) · 2.64 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using DotNet6WebAPI.Common;
using DotNet6WebAPI.Dapper;
using DotNet6WebAPI.Dapper.Mapping;
using DotNet6WebAPI.Dapper.Repositories;
using DotNet6WebAPI.Domain.Entities;
using DotNet6WebAPI.Filters;
using Hellang.Middleware.ProblemDetails;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Text.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSingleton<DapperContext>();
builder.Services.AddScoped<IStudentRepository, StudentRepository>();
builder.Services.AddScoped<Student>();
//dapper mapping
SetDapperMapper.Set();
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
//Global setting
//options.SerializerSettings.Converters.Add(new DotNet6WebAPI.DecimalConverter());
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Dotnet 6 demo Api",
Version = "v1",
Description = "description."
});
// Set the comments path for the Swagger JSON and UI.
// 设置注释
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
var xmlFile2 = $"DotNet6WebAPI.Domain.xml";
var xmlPath2 = Path.Combine(AppContext.BaseDirectory, xmlFile2);
c.IncludeXmlComments(xmlPath2);
c.SchemaFilter<EnumTypesSchemaFilter>(xmlPath2);
});
//add ProblemDetails
//为异常消息统一规范格式
//统一处理异常,为不同的异常设置不同的信息
builder.Services.AddProblemDetails(opts =>
{
opts.IncludeExceptionDetails = (ctx, ex) =>
{
return false;
};
opts.Map<CustomException>((ex) =>
{
var pd = StatusCodeProblemDetails.Create(StatusCodes.Status403Forbidden);
pd.Detail = ex.Message;
return pd;
});
opts.Map<Exception>((ex) =>
{
var pd = StatusCodeProblemDetails.Create(StatusCodes.Status500InternalServerError);
pd.Detail = ex.Message;
pd.Extensions.Add("key1", "value1");
pd.Extensions.Add("key2", 2);
return pd;
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();