不做码农 973c3281b2 Squashed commit of the following:
commit 1daa137d98a3a814e3617606b14c737dbb611f4f
Author: 不做码农 <599854767@qq.com>
Date:   Sat Apr 9 14:51:29 2022 +0800

    IPRatelimit添加白名单接口

commit d05690654b889ae3ab8f4add1b76a5859e1ab89a
Author: 不做码农 <599854767@qq.com>
Date:   Fri Apr 8 20:20:11 2022 +0800

    添加页签openPage支持传递参数

commit 861710079a26294c64d70eeadb7630bf83e3bfc4
Author: 不做码农 <599854767@qq.com>
Date:   Fri Apr 8 12:44:28 2022 +0800

    update FileHelper.cs

commit a0cf47c099533fabaf5bd389cf498f08eead2ef4
Author: 不做码农 <599854767@qq.com>
Date:   Thu Apr 7 13:30:47 2022 +0800

    优化代码生成模板

commit 5b376614d02c2d27b6e90252c2a3169adfb0e612
Author: 不做码农 <599854767@qq.com>
Date:   Thu Apr 7 13:30:13 2022 +0800

    IP限制增加百名单接口

commit 939ec56d1db4cad52f7b64555e16d52b5b061360
Author: 不做码农 <599854767@qq.com>
Date:   Mon Apr 4 21:48:27 2022 +0800

    fix 基础sql脚本bug

commit 19c738b974e14b62929dc69c2c6ac1e8540aad98
Author: 不做码农 <599854767@qq.com>
Date:   Mon Apr 4 18:53:02 2022 +0800

    新增加IPRateLimit限制

commit 6b0e6b11b3fdbb5ab53606cf4d0910ae30886365
Author: 不做码农 <599854767@qq.com>
Date:   Mon Apr 4 12:09:39 2022 +0800

    格式化代码

commit 1024471c64beef683b257b38d4904ab7cd509c82
Author: 不做码农 <599854767@qq.com>
Date:   Mon Apr 4 12:02:32 2022 +0800

    自定义异常新增获取LogAttribute属性
2022-04-09 15:06:45 +08:00

169 lines
6.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AspNetCoreRateLimit;
using Hei.Captcha;
using Infrastructure;
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading.Tasks;
using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Filters;
using ZR.Admin.WebApi.Framework;
using ZR.Admin.WebApi.Hubs;
using ZR.Admin.WebApi.Middleware;
namespace ZR.Admin.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
string corsUrls = Configuration["corsUrls"];
//配置跨域
services.AddCors(c =>
{
c.AddPolicy("Policy", policy =>
{
policy.WithOrigins(corsUrls.Split(',', StringSplitOptions.RemoveEmptyEntries))
.AllowAnyHeader()//允许任意头
.AllowCredentials()//允许cookie
.AllowAnyMethod();//允许任意方法
});
});
//注入SignalR实时通讯默认用json传输
services.AddSignalR(options =>
{
//客户端发保持连接请求到服务端最长间隔默认30秒改成4分钟网页需跟着设置connection.keepAliveIntervalInMilliseconds = 12e4;即2分钟
//options.ClientTimeoutInterval = TimeSpan.FromMinutes(4);
//服务端发保持连接请求到客户端间隔默认15秒改成2分钟网页需跟着设置connection.serverTimeoutInMilliseconds = 24e4;即4分钟
//options.KeepAliveInterval = TimeSpan.FromMinutes(2);
});
//消除Error unprotecting the session cookie警告
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection"));
//普通验证码
services.AddHeiCaptcha();
services.AddIPRate(Configuration);
services.AddSession();
services.AddMemoryCache();
services.AddHttpContextAccessor();
//绑定整个对象到Model上
services.Configure<OptionsSetting>(Configuration);
//jwt 认证
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddCookie()
.AddJwtBearer(o =>
{
o.TokenValidationParameters = JwtUtil.ValidParameters();
});
InjectServices(services, Configuration);
services.AddMvc(options =>
{
options.Filters.Add(typeof(GlobalActionMonitor));//全局注册
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeConverter());
options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeNullConverter());
});
services.AddSwaggerConfig();
}
// 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();
//使可以多次多去body内容
app.Use((context, next) =>
{
context.Request.EnableBuffering();
if (context.Request.Query.TryGetValue("access_token", out var token))
{
context.Request.Headers.Add("Authorization", $"Bearer {token}");
}
return next();
});
//开启访问静态文件/wwwroot目录文件要放在UseRouting前面
app.UseStaticFiles();
//开启路由访问
app.UseRouting();
app.UseCors("Policy");//要放在app.UseEndpoints前。
//app.UseAuthentication会启用Authentication中间件该中间件会根据当前Http请求中的Cookie信息来设置HttpContext.User属性后面会用到
//所以只有在app.UseAuthentication方法之后注册的中间件才能够从HttpContext.User中读取到值
//这也是为什么上面强调app.UseAuthentication方法一定要放在下面的app.UseMvc方法前面因为只有这样ASP.NET Core的MVC中间件中才能读取到HttpContext.User的值。
//1.先开启认证
app.UseAuthentication();
//2.再开启授权
app.UseAuthorization();
//开启session
app.UseSession();
//开启缓存
app.UseResponseCaching();
//恢复/启动任务
app.UseAddTaskSchedulers();
//使用全局异常中间件
app.UseMiddleware<GlobalExceptionMiddleware>();
//启用客户端IP限制速率
app.UseIpRateLimiting();
app.UseEndpoints(endpoints =>
{
//设置socket连接
endpoints.MapHub<MessageHub>("/msgHub");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
/// <summary>
/// 注册Services服务
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
private void InjectServices(IServiceCollection services, IConfiguration configuration)
{
services.AddAppService();
services.AddSingleton(new AppSettings(configuration));
//开启计划任务
services.AddTaskSchedulers();
//初始化db
DbExtension.AddDb(configuration);
//注册REDIS 服务
Task.Run(() =>
{
//RedisServer.Initalize();
});
}
}
}