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.

162 lines
5.9 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.Service.DjyService;
using djy_AfrApi.Filter;
using djy_AfrApi.HttpContextUser;
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.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 = "djy_AfrApi", Version = "v1" });
});
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", "djy_AfrApi 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.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}