.netcore webapi设置
一.跨域设置
1.ConfigureServices方法中注入
services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); });
2.在StartUp类中的Configure方法中使用
app.UseCors("CorsPolicy");
二.swagger使用
1.swagger的引用
引用Swashbuckle.AspNetCore和Swashbuckle.AspNetCore.Swagger
2.项目属性更改。勾选xml文档文件
3.在ConfigureServices中注册
#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
4.在Configure中添加中间件
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
5.项目启动
三.获取appsettings.json配置
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;"
}
}
2.单个获取配置文件方法
Configuration.GetConnectionString("Conn");
Configuration["ConnectionStrings:Conn"];
3.多个获取配置文件方法
添加配置对应的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<JWTConfig>(Configuration.GetSection("JWT"));//.AddMvc();
或
JWTConfig config = new JWTConfig();
Configuration.GetSection("JWT").Bind(config);
四.依赖注入配置
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);
}
2.Service为外部类库引用时直接注入dll
services.AddAssembly("VoiceCall.Service");
方式实现cs:
/// <summary>
/// 程序集依赖注入
/// </summary>
/// <param name="services">服务实例</param>
/// <param name="assemblyName">程序集名称。不带DLL</param>
/// <param name="serviceLifetime">依赖注入的类型 可为空</param>
public static void AddAssembly(this IServiceCollection services, string assemblyName, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
if (services == null)
throw new ArgumentNullException(nameof(services) + "为空");
if (String.IsNullOrEmpty(assemblyName))
throw new ArgumentNullException(nameof(assemblyName) + "为空");
Assembly assembly = GetAssemblyByName(assemblyName);
//var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyName);
if (assembly == null)
throw new DllNotFoundException(nameof(assembly) + ".dll不存在");
//找到当前程序集的类集合
var types = assembly.GetTypes();
//过滤筛选(是类文件,并且不是抽象类,不是泛型)
var list = types.Where(o => o.IsClass && !o.IsAbstract && !o.IsGenericType).ToList();
if (list == null && !list.Any())
return;
//遍历获取到的类
foreach (var type in list)
{
//然后获取到类对应的接口
var interfacesList = type.GetInterfaces();
//校验接口存在则继续
if (interfacesList == null || !interfacesList.Any())
continue;
//获取到接口(第一个)
var inter = interfacesList.First();
switch (serviceLifetime)
{
//根据条件,选择注册依赖的方法
case ServiceLifetime.Scoped:
//将获取到的接口和类注册进去
services.AddScoped(inter, type);
break;
case ServiceLifetime.Singleton:
services.AddScoped(inter, type);
break;
case ServiceLifetime.Transient:
services.AddTransient(inter, type);
break;
}
}
}
/// <summary>
/// 通过程序集的名称加载程序集
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
public static Assembly GetAssemblyByName(string assemblyName)
{
return AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName));
}
3.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);
}
}
}
}