24小时一体机服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

287 lines
10 KiB

using Elight.Logic;
using Elight.Utility;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using SqlSugar;
using System.Text;
using _24Hour.Controllers.Common;
using System.IdentityModel.Tokens.Jwt;
using Quartz.Impl;
using Quartz;
using Elight.Logic.Job;
using Quartz.Spi;
using Microsoft.IdentityModel.Logging;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
#region builder
var builder = WebApplication.CreateBuilder(args);
var Configuration = builder.Configuration;
builder.WebHost.UseUrls(Configuration.GetSection("UrlsConfiguration:Urls").Value.Split(","));
// Add services to the container.
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.DateTimeNullableConverter());
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.NullableConverter<long>());
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.NullableConverter<int>());
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.NullableConverter<double>());
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.NullableConverter<decimal>());
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.NullableConverter<float>());
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.NullableConverter<Guid>());
options.JsonSerializerOptions.Converters.Add(new Elight.Utility.NullableConverter<bool>());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
#region Swagger<EFBFBD>ļ<EFBFBD>
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "24Сʱһ<EFBFBD><EFBFBD><EFBFBD><EFBFBD> API", Version = "v1" });
//<EFBFBD>ڽӿ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> [HiddenApi]<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֹ<EFBFBD><EFBFBD>Swagger<EFBFBD>ĵ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
c.DocumentFilter<HiddenApiFilter>();
c.OrderActionsBy(o => o.RelativePath);
var basePath = System.AppDomain.CurrentDomain.BaseDirectory;//<EFBFBD><EFBFBD>ȡӦ<EFBFBD>ó<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ŀ¼<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ԣ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ܹ<EFBFBD><EFBFBD><EFBFBD>Ŀ¼Ӱ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ô˷<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȡ·<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var xmlPath = Path.Combine(basePath, "24Hour.xml");
if (File.Exists(xmlPath))//<EFBFBD><EFBFBD><EFBFBD><EFBFBD>û<EFBFBD>и<EFBFBD><EFBFBD>ļ<EFBFBD>ʱ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
c.IncludeXmlComments(xmlPath, true);
//<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Jwt<EFBFBD><EFBFBD>֤<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Value: Bearer {token}",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
});
#endregion
// <EFBFBD><EFBFBD><EFBFBD>ÿ<EFBFBD><EFBFBD><EFBFBD>
builder.Services.AddCors(policy =>
{
policy.AddPolicy("CorsPolicy", opt => opt
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("X-Pagination"));
});
//builder.Services.AddCors(options => options.AddPolicy("CorsPolicy",
//c =>
//{
// c.WithOrigins(Configuration.GetSection("UrlsConfiguration:CorUrls").Value.Split(',', StringSplitOptions.RemoveEmptyEntries))
// .AllowAnyHeader() // <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>κα<EFBFBD>ͷ(<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>д<EFBFBD><EFBFBD>AllowAnyMethod<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȥ)
// .AllowAnyMethod() // <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>κη<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
// .SetIsOriginAllowed(o => true) // =AllowAnyOrigin()
// .AllowCredentials();
//}));
//<EFBFBD><EFBFBD><EFBFBD><EFBFBD>jwt toekn
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
// <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
})
.AddJwtBearer(options =>
{
// <EFBFBD><EFBFBD><EFBFBD><EFBFBD>JWT<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤ѡ<EFBFBD><EFBFBD>
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration.GetSection("JwtConfiguration:Issuer").Value,
ValidAudience = Configuration.GetSection("JwtConfiguration:Audience").Value,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("JwtConfiguration:Jwtkey").Value)),
ClockSkew = TimeSpan.Zero
};
//<EFBFBD>ص<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ж<EFBFBD><EFBFBD><EFBFBD>WebSocket<EFBFBD><EFBFBD>·<EFBFBD><EFBFBD>(https://www.cnblogs.com/fger/p/11811190.html)
options.Events = new JwtBearerEvents
{
OnMessageReceived = (context) =>
{
if (!context.HttpContext.Request.Path.HasValue) return Task.CompletedTask;
//<EFBFBD>ص<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ж<EFBFBD><EFBFBD><EFBFBD>WebSocket<EFBFBD><EFBFBD>·<EFBFBD><EFBFBD>
var accessToken = context.HttpContext.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (string.IsNullOrWhiteSpace(accessToken) || !path.StartsWithSegments("/ws")) return Task.CompletedTask;
context.Token = accessToken;
return Task.CompletedTask;
},
//<EFBFBD>˴<EFBFBD>ΪȨ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤ʧ<EFBFBD>ܺ󴥷<EFBFBD><EFBFBD><EFBFBD><EFBFBD>¼<EFBFBD>
OnChallenge = context =>
{
//<EFBFBD>˴<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><EFBFBD>ֹ.Net CoreĬ<EFBFBD>ϵķ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͺ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݽ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ҪŶ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
context.HandleResponse();
//<EFBFBD>Զ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Լ<EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD><EFBFBD><EFBFBD>ص<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݽ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD><EFBFBD><EFBFBD>ص<EFBFBD><EFBFBD><EFBFBD>Json<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͨ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Newtonsoft.Json<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ת<EFBFBD><EFBFBD>
var payload = new { StatusCode = 0, Message = "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤ʧ<EFBFBD>ܣ<EFBFBD>" };
//<EFBFBD>Զ<EFBFBD><EFBFBD><EFBFBD>ص<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
context.Response.ContentType = "application/json";
//<EFBFBD>Զ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>״̬<EFBFBD>룬Ĭ<EFBFBD><EFBFBD>Ϊ401 <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ij<EFBFBD> 200
context.Response.StatusCode = StatusCodes.Status200OK;
//context.Response.StatusCode = StatusCodes.Status401Unauthorized;
//<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Json<EFBFBD><EFBFBD><EFBFBD>ݽ<EFBFBD><EFBFBD><EFBFBD>
context.Response.WriteAsync(Convert.ToString(payload));
return Task.FromResult(0);
}
};
}).AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
//builder.Services.AddAuthorization();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<WebSocketController>();
builder.Services.TryAddSingleton<User, User>();
builder.Services.TryAddSingleton<WriteSysLog, WriteSysLog>(); //WriteSysLog
builder.Services.AddScoped<SqlSugarClient>(sp =>
{
var connectionString = Configuration.GetSection("ConnectionStrings:MySQLConnString").Value;
var db = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = connectionString,
DbType = SqlSugar.DbType.MySql,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
return db;
});
#region <EFBFBD><EFBFBD>ʱ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
// <EFBFBD><EFBFBD><EFBFBD><EFBFBD>Quartz.NET<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
builder.Services.TryAddSingleton<IJobFactory, JobFactory>();
builder.Services.TryAddSingleton<ISchedulerFactory, StdSchedulerFactory>();
builder.Services.TryAddSingleton<WsJob>();
builder.Services.TryAddSingleton<YgJob>();
builder.Services.AddHostedService<QuartzHostedService>(); // ע<EFBFBD><EFBFBD>Quartz.NET<EFBFBD><EFBFBD><EFBFBD>йܷ<EFBFBD><EFBFBD><EFBFBD>
//Task.Factory.StartNew(() =>
//{
// try
// {
// while (true)
// {
// Thread.Sleep(60 * 1000);
// ClearMemory();
// }
// }
// catch (Exception ex)
// {
// }
//});
//Task.Factory.StartNew(() =>
//{
// RunJob().Wait();
//});
#endregion
#endregion
#region APP
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
#region websockets<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromMinutes(2)
});
//app.UseMiddleware<WebSocketMiddleware>();
#endregion
app.UseStaticFiles();
//app.UseHttpsRedirection();
//·<EFBFBD><EFBFBD>
app.UseRouting();
app.UseAuthentication(); // <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤<EFBFBD>м<EFBFBD><EFBFBD><EFBFBD>
app.UseAuthorization(); // <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ȩ<EFBFBD>м<EFBFBD><EFBFBD><EFBFBD>
//app.MapControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
#region swagger
app.UseSwagger();// <EFBFBD><EFBFBD><EFBFBD><EFBFBD>Swagger<EFBFBD>м<EFBFBD><EFBFBD><EFBFBD>
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "24Сʱһ<EFBFBD><EFBFBD><EFBFBD><EFBFBD> API V1");
c.RoutePrefix = string.Empty;
});
#endregion
app.UseCors("CorsPolicy");
app.Run();
#endregion
#region <EFBFBD><EFBFBD>ʱ
static void ClearMemory()
{
try
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
}
}
static async Task RunJob()
{
try
{
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
IScheduler scheduler = await factory.GetScheduler();
// <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
await scheduler.Start();
#region ͨ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ÿ33<EFBFBD><EFBFBD>ִ<EFBFBD><EFBFBD>3
IJobDetail job3 = JobBuilder.Create<WsJob>()
.WithIdentity("job3", SchedulerConstants.DefaultGroup)
.Build();
var trigger3 = TriggerBuilder.Create()
.WithIdentity("trigger3") // <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
.StartAt(DateTime.Now) // <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʼʱ<EFBFBD><EFBFBD>
.ForJob("job3", SchedulerConstants.DefaultGroup) //<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><EFBFBD>һ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
.WithCronSchedule("*/20 * * * * ?")
.UsingJobData("k", 321)
.Build();
await scheduler.ScheduleJob(job3, trigger3);
#endregion
}
catch (SchedulerException se)
{
await Console.Error.WriteLineAsync(se.ToString());
}
}
#endregion