愿你出走半生,归来仍是少年!
Api项目作为整个解决方案的入口,主要体现出了其在配置上的重要性。
1.自动Api配置
Configure<AbpAspNetCoreMvcOptions>(options =>
{
针对指定的模块进行自动API控制器生产
options.ConventionalControllers.Create(typeof(LandManagerApplicationModule).Assembly, opts => {
opts.UseV3UrlStyle = true;
});
});
2.鉴权配置 (此处采用的非对称)
//设置公钥,用于token 解密
var publicKey = configuration["App:PublicKey"];
var helper = new RSAHelper(RSAType.RSA2, Encoding.UTF8, null, publicKey);
var rsa = helper.CreateRsaProviderFromPublicKey(publicKey);
var key = new RsaSecurityKey(rsa);
//添加jwt token 验证策略
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//公钥验签
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = key//拿到SecurityKey
};
});
3.汉化配置
Configure<AbpLocalizationOptions>(options =>
{
options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
});
4.跨域配置
context.Services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName,builder =>
{
builder
.WithOrigins(
configuration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray()
)
.WithAbpExposedHeaders()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
5.Swagger配置
context.Services.AddAbpSwaggerGen(opts => {
//文档名称
opts.SwaggerDoc(configuration["App:Name"], new OpenApiInfo
{
//版本
Version = configuration["App:ApiVersion"],
//标题
Title = configuration["App:NickName"],
//描述
Description = configuration["App:Description"]+ "<br/><br/>[接口更新日志](../changelog.html)",
});
var basePath = AppContext.BaseDirectory;
DirectoryInfo d = new DirectoryInfo(basePath);
FileInfo[] files = d.GetFiles("*.xml");
var xmls = files.Select(a => Path.Combine(basePath, a.FullName)).ToList();
foreach (var item in xmls)
{
opts.IncludeXmlComments(item);
}
opts.DocInclusionPredicate((docName, description) => true);
//swagger页面 的 jwt Token验证定义
opts.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
In = ParameterLocation.Header,
Scheme = "bearer",
Type = SecuritySchemeType.Http,//直接在输入框中输入认证信息,不需要在开头添加Bearer;若使用ApiKey 需要在框中输入Bearer {token}(注意两者之间是一个空格)
BearerFormat = "JWT",
Description = "请输入接口返回的Token"
});
//验证类型为 Bearer
opts.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id =JwtBearerDefaults.AuthenticationScheme }
},
new List<string>()
}
});
});
6.审计日志配置
Configure<AbpAuditingOptions>(options =>
{
options.IsEnabledForGetRequests = true;//记录get请求
});