You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

177 lines
6.3 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Common;
using djy.Model;
using djy.Service.DjyService;
using djy_AfrApi.Filter;
using djy_AfrApi.Middlewares;
using FreeRedis;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Logging;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.IO;
using System;
using System.Linq;
using System.Reflection;
namespace djy_AfrApi
{
public class Startup
{
public Startup(IConfiguration configuration,IHostEnvironment hostEnvironment)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped<IUser, AspNetUser>();
services.AddControllers(o =>
{
o.Filters.Add(typeof(GlobalExceptionsFilter));
})
.AddNewtonsoftJson(options =>
{
//忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//是否使用驼峰样式的key
//options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//设置时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//忽略Model中为null的属性
//options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
//设置本地时间而非UTC时间
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
//添加Enum转string
options.SerializerSettings.Converters.Add(new StringEnumConverter());
})
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var result = new BadRequestObjectResult(context.HttpContext);
return result;
};
});
services.AddHttpClient();
//读取配置信息
Configuration.Bind("WebConfig", sysOptionConfig.Webconfig);
sysOptionConfig._Configuration = Configuration;
// 注入redis客户端
//RedisClient cli = new RedisClient(sysOptionConfig.Webconfig.Redis + ",defaultDatabase=" + sysOptionConfig.Webconfig.RedisDb);
//services.AddSingleton<IRedisClient>(cli);
services.AddAuthentication("Bearer").AddJwtBearer("Bearer", option =>
{
option.Authority = sysOptionConfig.Webconfig.IdentServerUrl;//授权服务的URl地址
option.RequireHttpsMetadata = false;//是否使用了https
option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateAudience = false };
IdentityModelEventSource.ShowPII = true;
});
//初始化数据库连接池
DbContext.DbBusInit();
////批量循环依赖注册
var ISList = Assembly.Load("djy.IService").GetTypes().Where(w => w.Name.EndsWith("Service") && w.Name.StartsWith("I"));
var Slist = Assembly.Load("djy.Service").GetTypes().Where(w => w.Name.EndsWith("Service"));
foreach (var Is in ISList)
{
var sname = Slist.FirstOrDefault(w => w.Name == Is.Name.Substring(1));
if (sname != null)
{
services.AddTransient(Is, sname);
}
}
services.AddAutoMapper(typeof(AutoMapperConfig));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AFR Api文档", Version = "v1" });
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "djy_AfrApi.xml");
c.IncludeXmlComments(xmlPath, true);
var xmlModelPath = Path.Combine(basePath, "djy.Model.xml");
c.IncludeXmlComments(xmlModelPath);
c.UseInlineDefinitionsForEnums();
});
IOC.container = services;
}
// 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();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AFR Api文档 v1"));
}
// 记录请求响应数据
app.UseRequRespLogMiddleware();
// 处理特殊情况下的响应格式401、403
app.UseUnifyResultMiddleware();
// 异常处理中间件
app.UseExceptionHandlerMiddle();
app.UseRouting();
DefaultFilesOptions defaultFiles = new DefaultFilesOptions();
defaultFiles.DefaultFileNames.Clear();
defaultFiles.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defaultFiles);
app.UseStaticFiles();
//跨域处理
app.UseCors(builder =>
{
builder.AllowAnyHeader();
builder.AllowAnyMethod();
//builder.WithOrigins("http://www.baidu.com");//跨域配置
builder.AllowAnyOrigin();
});
//认证
app.UseAuthentication();
//授权
app.UseAuthorization();
// 二次验证授权并保存当前登录人User对象为了和ISF、AMS逻辑保持一致
app.UseNextAuthorizationMiddle();
// 公共字典数据缓存中间件
app.UseCommonCacheMiddleware();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}