203 lines
7.4 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 Infrastructure.Converter;
using Microsoft.AspNetCore.DataProtection;
using NLog.Web;
using System.Text.Json;
using BloomFilter.CSRedis.Configurations;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Options;
using ZR.Admin.Grpc;
using ZR.Admin.Grpc.Extensions;
using ZR.Admin.WebApi.Extensions;
using ZR.Infrastructure.Cache;
using ZR.Infrastructure.WebExtensions;
using ZR.ServiceCore.Services.IService;
using ZR.ServiceCore.Signalr;
using ZR.ServiceCore.SqlSugar;
using IpRateLimitPolicy = AspNetCoreRateLimit.IpRateLimitPolicy;
var builder = WebApplication.CreateBuilder(args);
//load json config by loginVerify
builder.Configuration.AddJsonFile("loginVerifyConf.json", true, true);
// NLog: Setup NLog for Dependency injection
//builder.Logging.ClearProviders();
builder.Host.UseNLog();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//注入HttpContextAccessor
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// 跨域配置
builder.Services.AddCors(builder.Configuration);
// Grpc
builder.Services.AddGrpc();
// 显示logo
// builder.Services.AddLogo();
//消除Error unprotecting the session cookie警告
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection"));
//普通验证码
builder.Services.AddCaptcha(builder.Configuration);
//IPRatelimit
builder.Services.AddIPRate(builder.Configuration);
//builder.Services.AddSession();
builder.Services.AddHttpContextAccessor();
//绑定整个对象到Model上
builder.Services.Configure<OptionsSetting>(builder.Configuration);
//jwt 认证
builder.Services.AddJwt();
//配置文件
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
//app服务注册
builder.Services.AddAppService();
//开启计划任务
builder.Services.AddTaskSchedulers();
//注册REDIS 服务
var openRedis = builder.Configuration["RedisServer:open"];
if (openRedis == "1")
{
RedisServer.Initalize();
builder.Services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
builder.Services.AddBloomFilter(setupAction =>
{
setupAction.UseCSRedis(new FilterCSRedisOptions
{
Name = "Redis1",
RedisKey = "BloomFilter",
ConnectionStrings = new List<string>
{
AppSettings.GetConfig("RedisServer:Cache")
}
});
});
}
builder.Services.AddMvc(options =>
{
options.Filters.Add(typeof(GlobalActionMonitor));//全局注册
})
.AddJsonOptions(options =>
{
//options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString;
options.JsonSerializerOptions.WriteIndented = true;
options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeConverter());
options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeNullConverter());
options.JsonSerializerOptions.Converters.Add(new StringConverter());
//PropertyNamingPolicy属性用于前端传过来的属性的格式策略目前内置的仅有一种策略CamelCase
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
//options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;//属性可以忽略大小写格式,开启后性能会降低
});
//注入SignalR实时通讯默认用json传输
builder.Services.AddSignalR()
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
builder.Services.AddSwaggerConfig();
// using var channel = GrpcChannel.ForAddress("https://localhost:7025");
// var client = new Greeter.GreeterClient(channel);
// var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });
// Console.WriteLine("Greeting: " + reply.Message);
//
// var blockClient = new Block.BlockClient(channel);
// var blockReply = await blockClient.GetBlockAsync(new BlockRequest { In = "asads" });
// Console.WriteLine("BlockReply: " + blockReply.Out);
builder.Services.AddGrpcServiceConfiguration(builder.Configuration);
var app = builder.Build();
InternalApp.ServiceProvider = app.Services;
InternalApp.Configuration = builder.Configuration;
InternalApp.WebHostEnvironment = app.Environment;
//初始化db
builder.Services.AddDb(app.Environment);
//使用全局异常中间件
app.UseMiddleware<GlobalExceptionMiddleware>();
//请求头转发
//ForwardedHeaders中间件会自动把反向代理服务器转发过来的X-Forwarded-For客户端真实IP以及X-Forwarded-Proto客户端请求的协议自动填充到HttpContext.Connection.RemoteIPAddress和HttpContext.Request.Scheme中这样应用代码中读取到的就是真实的IP和真实的协议了不需要应用做特殊处理。
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto
});
app.Use((context, next) =>
{
//设置可以多次获取body内容
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.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
//开启缓存
app.UseResponseCaching();
if (builder.Environment.IsProduction())
{
//恢复/启动任务
app.UseAddTaskSchedulers();
}
//使用swagger
app.UseSwagger();
//启用客户端IP限制速率
// app.UseIpRateLimiting();
app.UseMiddleware<CustomIpRateLimitMiddleware>();
app.UseRateLimiter();
//设置socket连接
app.MapHub<MessageHub>("/msgHub");
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllers();
using (var serviceScope = app.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
// get the IpPolicyStore instance
var ipPolicyStore = services.GetRequiredService<IIpPolicyStore>();
// seed IP data from appsettings
ipPolicyStore.SeedAsync().GetAwaiter().GetResult();
var optionsAccessor = services.GetRequiredService<IOptions<IpRateLimitOptions>>();
var ipRateLimitPolicyService = services.GetRequiredService<IIpRateLimitPolicyService>();
var ipRateLimitPolicies = ipRateLimitPolicyService.Queryable()
.Includes(it => it.Rules.Where(r => r.Flag == '1').ToList())
.Where(it => it.Flag == '1')
.ToListAsync().GetAwaiter().GetResult();
var pol = await ipPolicyStore.GetAsync(optionsAccessor.Value.IpPolicyPrefix);
pol.IpRules.AddRange(ipRateLimitPolicies.Adapt<List<IpRateLimitPolicy>>());
await ipPolicyStore.SetAsync(optionsAccessor.Value.IpPolicyPrefix, pol);
var greeterClient = services.GetRequiredService<Greeter.GreeterClient>();
var helloReply = await greeterClient.SayHelloAsync(new HelloRequest
{
Name = "gree"
});
// Console.WriteLine(helloReply);
}
app.Run();