using HL_FristAidPlatform_Token;
using log4net;
using log4net.Config;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace HL_FristAidPlatform_Service
{
///
/// Startup
///
public class Startup
{
private string version = "V4.3";
///
/// Startup
///
///
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
}
///
/// Configuration
///
public IConfiguration Configuration { get; }
///
/// ConfigureServices
///
///
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#region SignalR
services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
//builder.AllowAnyOrigin("http://47.112.158.86:4999").AllowAnyHeader().AllowAnyMethod().AllowCredentials();
builder.WithOrigins("http://47.112.158.86:4998", "http://47.112.158.86:5003", "http://47.112.158.86:5004", "http://47.112.158.86:51001", "http://112.53.108.22:51001", "http://112.53.108.22:51002", "https://api.map.baidu.com/geocoder", "http://47.112.158.86:5000", "http://220.170.196.249:51001/", "http://220.170.196.249:51002/")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}));
services.AddSignalR();
services.AddControllers();
#endregion
services.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
//CamelCasePropertyNamesContractResolver 驼峰命名法,首字母小写。如果变量全为大写,比如:NAME,返回的是 name
#region Swagger api 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("Public", new OpenApiInfo
{
Version = version,
Title = "湖南首辰急危重症平台",
Description = "WebAPI",
});
//c.DocumentFilter();
c.SwaggerDoc("QX", new OpenApiInfo { Title = "权限模块", Version = version });
c.SwaggerDoc("JC", new OpenApiInfo { Title = "基础数据模块", Version = version });
c.SwaggerDoc("XT", new OpenApiInfo { Title = "胸痛业务模块", Version = version });
c.SwaggerDoc("CZ", new OpenApiInfo { Title = "卒中业务模块", Version = version });
c.SwaggerDoc("CS", new OpenApiInfo { Title = "创伤业务模块", Version = version });
c.SwaggerDoc("YCF", new OpenApiInfo { Title = "危重孕产妇业务模块", Version = version });
c.SwaggerDoc("YQJJ", new OpenApiInfo { Title = "院前急救业务模块", Version = version });
c.SwaggerDoc("JZFZ", new OpenApiInfo { Title = "急诊分诊业务模块", Version = version });
c.SwaggerDoc("ZCGWSC", new OpenApiInfo { Title = "卒中高危筛查业务模块", Version = version });
c.SwaggerDoc("YTJ", new OpenApiInfo { Title = "一体机软件模块", Version = version });
//添加注释服务
//var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var basePath = Directory.GetCurrentDirectory();
var xmlPath = Path.Combine(basePath, "HL_FristAidPlatform_Service.xml");
var entityXmlPath = Path.Combine(basePath, "HL_FristAidPlatform_Models.xml");
var helpXmlPath = Path.Combine(basePath, "HL_FristAidPlatform_Help.xml");
c.IncludeXmlComments(xmlPath, true);
c.IncludeXmlComments(entityXmlPath, true);
c.IncludeXmlComments(helpXmlPath, true);
//添加header验证信息
//c.OperationFilter();
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT授权",//"JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
services.AddHealthChecks();
});
#endregion
#region 认证
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ClockSkew = TimeSpan.FromSeconds(30),
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = "wr",//Audience
ValidIssuer = "API",//Issuer,这两项和前面签发jwt的设置一致
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.JWTSecretKey)),//拿到SecurityKey
};
o.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
#endregion
#region 授权
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdd", policy => policy.RequireRole("ADD").Build());
options.AddPolicy("RequireUpdate", policy => policy.RequireRole("UPDATE").Build());
options.AddPolicy("RequireGet", policy => policy.RequireRole("GET").Build());
options.AddPolicy("RequireDelete", policy => policy.RequireRole("DELETE").Build());
});
#endregion
//配置 SignalR 服务,进行依赖注入
services.AddSignalR();
//services.AddWebSocketManager();
//services.AddTimedJob();
}
///
///
///
///
///
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
#region Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/Public/swagger.json", "公共模块");
c.SwaggerEndpoint("/swagger/QX/swagger.json", "权限模块");
c.SwaggerEndpoint("/swagger/JC/swagger.json", "基础数据模块");
c.SwaggerEndpoint("/swagger/XT/swagger.json", "胸痛业务模块");
c.SwaggerEndpoint("/swagger/CZ/swagger.json", "卒中业务模块");
c.SwaggerEndpoint("/swagger/CS/swagger.json", "创伤业务模块");
c.SwaggerEndpoint("/swagger/YCF/swagger.json", "孕产妇业务模块");
c.SwaggerEndpoint("/swagger/YQJJ/swagger.json", "院前急救业务模块");
c.SwaggerEndpoint("/swagger/JZFZ/swagger.json", "急诊分诊务模块");
c.SwaggerEndpoint("/swagger/ZCGWSC/swagger.json", "卒中高危筛查业务模块");
c.SwaggerEndpoint("/swagger/YTJ/swagger.json", "一体机软件模块");
c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
});
#endregion
app.UseRouting();
//使用跨域
app.UseCors("CorsPolicy");
//认证
app.UseAuthentication();
//授权
app.UseAuthorization();
app.UseStaticFiles();
// signalr
app.UseSignalRSendMildd();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub("/signalr/chatHub");
});
app.UseWebSockets();
//app.MapSockets("",ServiceProvider.GetService());
//app.UseTimedJob();
}
}
}