.netcore webapi设置
2021-03-05 00:28
标签:项目 exception email 联系 single except hosts eric 根据 一.跨域设置 2.在StartUp类中的Configure方法中使用 二.swagger使用 2.项目属性更改。勾选xml文档文件 3.在ConfigureServices中注册 4.在Configure中添加中间件 5.项目启动 三.获取appsettings.json配置 2.单个获取配置文件方法 3.多个获取配置文件方法 通过管道注册 四.依赖注入配置 通过反射获取方法的接口并注入 2.Service为外部类库引用时直接注入dll 方式实现cs: 3.Service为外部类库引用时通过配置文件动态依赖注入 .netcore webapi设置 标签:项目 exception email 联系 single except hosts eric 根据 原文地址:https://www.cnblogs.com/papermask/p/12910687.html
1.ConfigureServices方法中注入services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); });
app.UseCors("CorsPolicy");
1.swagger的引用引用Swashbuckle.AspNetCore和Swashbuckle.AspNetCore.Swagger
#region swagger
//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1", //版本
Title = "hl‘s API", //标题
Description = "API描述",//描述
TermsOfService = "None",
Contact = new Contact //联系人信息
{
Name = "**",
Email = string.Empty,
}
});
// 为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
var xmlPath = Path.Combine(basePath, "Test.xml");//xml路径名称
c.IncludeXmlComments(xmlPath);
});
#endregion
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
1.文件中配置{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"JWT": {
"Issuer": "PaperMask",
"Audience": "Audience",
"IssuerSigningKey": "PaperMask007",
"AccessTokenExpiresMinutes": "30"
},
"ConnectionStrings": {
"Conn": "Host=.;Database=TestDb;User ID=sa;Password=123456;"
}
}
Configuration.GetConnectionString("Conn");
Configuration["ConnectionStrings:Conn"];
添加配置对应的cs文件public class JWTConfig
{
public string Issuer { get; set; }
public string Audience { get; set; }
public string IssuerSigningKey { get; set; }
public double AccessTokenExpiresMinutes { get; set; }
}
services.Configure
1.
通过反射加载程序集中所有以Service结尾且不以I开头的方法var assembly = Assembly.GetExecutingAssembly().DefinedTypes.Where(a => a.Name.EndsWith("Service") && !a.Name.StartsWith("I"));
foreach (var item in assembly)
{
services.AddTransient(item.GetInterfaces().FirstOrDefault(), item);
}
services.AddAssembly("VoiceCall.Service");
///
string assemblies = Configuration["Assembly:FunctionAssembly"];
if (!string.IsNullOrEmpty(assemblies))
{
foreach (var item in assemblies.Split(‘|‘))
{
Assembly assembly = Assembly.Load(item);
foreach (var implement in assembly.GetTypes())
{
Type[] interfaceType = implement.GetInterfaces();
foreach (var service in interfaceType)
{
services.AddTransient(service, implement);
}
}
}
}