160 lines
		
	
	
		
			4.9 KiB
		
	
	
	
		
			C#
		
	
	
	
			
		
		
	
	
			160 lines
		
	
	
		
			4.9 KiB
		
	
	
	
		
			C#
		
	
	
	
using LY.App.Extensions;
 | 
						|
using Microsoft.AspNetCore.Mvc;
 | 
						|
using Microsoft.OpenApi.Models;
 | 
						|
using Newtonsoft.Json.Serialization;
 | 
						|
using Newtonsoft.Json;
 | 
						|
using SqlSugar;
 | 
						|
using Microsoft.AspNetCore.Cors.Infrastructure;
 | 
						|
using LY.App.Common.Redis;
 | 
						|
using LY.App.Service;
 | 
						|
using LY.App.Model;
 | 
						|
using LY.App.MiddleWare;
 | 
						|
using LY.App.Common.WebSocket;
 | 
						|
using Microsoft.Extensions.FileProviders;
 | 
						|
 | 
						|
var builder = WebApplication.CreateBuilder(args);
 | 
						|
 | 
						|
// Add services to the container.
 | 
						|
 | 
						|
builder.Services.AddControllers(options =>
 | 
						|
{
 | 
						|
    // 禁用隐式 [Required] 属性标记对非可空引用类型的属性
 | 
						|
    options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
 | 
						|
}).AddNewtonsoftJson()
 | 
						|
                .AddNewtonsoftJson(NewtonsoftInitialize); ;
 | 
						|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 | 
						|
builder.Services.AddEndpointsApiExplorer();
 | 
						|
builder.Services.AddSwaggerGen(
 | 
						|
    options =>
 | 
						|
    {
 | 
						|
        options.SwaggerDoc("v1", new OpenApiInfo()
 | 
						|
        {
 | 
						|
            Title = "LY.App-Api",
 | 
						|
            Version = "v1",
 | 
						|
            Description = "Api接口文档",
 | 
						|
        });
 | 
						|
        var path = Path.Combine(AppContext.BaseDirectory, "ly.xml");
 | 
						|
        options.IncludeXmlComments(path, true);
 | 
						|
        options.OrderActionsBy(_ => _.RelativePath);
 | 
						|
    });
 | 
						|
builder.Services.AddCors(CorsOptionsEvnet);
 | 
						|
//redis 
 | 
						|
string redisConnection = builder.Configuration.GetValue<string>("Redis:ConnectionString") ?? "localhost:6379";
 | 
						|
 | 
						|
// 注册 RedisService
 | 
						|
builder.Services.AddSingleton(new RedisService(redisConnection));
 | 
						|
builder.Services.AddTransient<TokenValidationMiddleware>();
 | 
						|
////注册SignalR
 | 
						|
builder.Services.AddSignalR();
 | 
						|
builder.Services.AddHttpClient();
 | 
						|
//注册依赖注入
 | 
						|
builder.Services.ServicesAutoInjectionExtension();
 | 
						|
//数据库
 | 
						|
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
 | 
						|
//sqlsugar
 | 
						|
builder.Services.AddTransient<SqlSugarClient>(sp =>
 | 
						|
{
 | 
						|
    return new SqlSugarClient(new ConnectionConfig()
 | 
						|
    {
 | 
						|
        ConnectionString = connectionString,
 | 
						|
        DbType = DbType.MySql,
 | 
						|
        IsAutoCloseConnection = true,
 | 
						|
        ConfigureExternalServices = new ConfigureExternalServices()
 | 
						|
        {
 | 
						|
            EntityService = (x, p) => //处理列名
 | 
						|
            {
 | 
						|
                //最好排除DTO类
 | 
						|
                p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);//ToUnderLine驼峰转下划线方法
 | 
						|
            }
 | 
						|
        },
 | 
						|
        InitKeyType = InitKeyType.Attribute // 使用属性名作为列名
 | 
						|
    }, db =>
 | 
						|
    {
 | 
						|
 | 
						|
#if DEBUG
 | 
						|
        db.Aop.OnLogExecuting = (sql, pars) =>
 | 
						|
        {
 | 
						|
            Console.WriteLine(sql + "参数值:" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
 | 
						|
        };
 | 
						|
        //创建数据库和表的语句仅执行一次 
 | 
						|
        //db.DbMaintenance.CreateDatabase();
 | 
						|
        //db.CodeFirst.SetStringDefaultLength(2000).InitTables(typeof(UserEntity));
 | 
						|
#endif
 | 
						|
        //过滤器写在这儿就行了
 | 
						|
        // db.QueryFilter.AddTableFilter<IDeleted>(it => it.IsDeleted == false);
 | 
						|
    });
 | 
						|
});
 | 
						|
 | 
						|
//检测并创建图片存储文件目录
 | 
						|
string path = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "Img"));
 | 
						|
if (!Directory.Exists(path))
 | 
						|
{
 | 
						|
    Directory.CreateDirectory(path);
 | 
						|
}
 | 
						|
 | 
						|
SnowFlakeSingle.WorkId = Convert.ToInt32(builder.Configuration.GetSection("SnowFlakeWordId")?.Value ?? "1");
 | 
						|
var app = builder.Build();
 | 
						|
ServiceLocator.Instance = app.Services;
 | 
						|
var device = app.Services.GetService<DeviceService>();
 | 
						|
await device?.Init();
 | 
						|
app.UseStaticFiles(new StaticFileOptions()
 | 
						|
{
 | 
						|
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Img")),
 | 
						|
    RequestPath = "/upload"
 | 
						|
});
 | 
						|
// Configure the HTTP request pipeline.
 | 
						|
if (app.Environment.IsDevelopment())
 | 
						|
{
 | 
						|
 | 
						|
}
 | 
						|
app.UseSwagger();
 | 
						|
app.UseSwaggerUI();
 | 
						|
//路由匹配
 | 
						|
app.UseRouting();
 | 
						|
app.UseAuthorization();
 | 
						|
app.UseCors("CorsPolicy");
 | 
						|
 | 
						|
//异常中间件
 | 
						|
app.UseMiddleware<CustomErrorMiddleware>();
 | 
						|
//token验证中间件
 | 
						|
app.UseMiddleware<TokenValidationMiddleware>();
 | 
						|
//执行匹配的端点
 | 
						|
app.UseEndpoints(endpoints =>
 | 
						|
{
 | 
						|
    endpoints.MapHub<SocketHub>("/websocket");
 | 
						|
    endpoints.MapControllers();
 | 
						|
});
 | 
						|
 | 
						|
app.MapControllers();
 | 
						|
app.Run();
 | 
						|
 | 
						|
static void NewtonsoftInitialize(MvcNewtonsoftJsonOptions options)
 | 
						|
{
 | 
						|
    //忽略循环引用
 | 
						|
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 | 
						|
    //期类型默认格式化处理
 | 
						|
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
 | 
						|
    //解决命名不一致问题 
 | 
						|
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
 | 
						|
    //空值处理
 | 
						|
    //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
 | 
						|
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
 | 
						|
}
 | 
						|
/// <summary>
 | 
						|
/// 跨域配置事件
 | 
						|
/// </summary>
 | 
						|
static void CorsOptionsEvnet(CorsOptions options)
 | 
						|
{
 | 
						|
    options.AddPolicy("CorsPolicy", cors =>
 | 
						|
    {
 | 
						|
        cors.AllowAnyOrigin();
 | 
						|
        cors.AllowAnyHeader();
 | 
						|
        cors.AllowAnyMethod();
 | 
						|
    });
 | 
						|
}
 | 
						|
public static class ServiceLocator
 | 
						|
{
 | 
						|
    public static IServiceProvider Instance { get; set; }
 | 
						|
}
 | 
						|
 |