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.
207 lines
7.8 KiB
207 lines
7.8 KiB
using Elight.Logic; |
|
using Elight.Utility; |
|
using Microsoft.AspNetCore.Authentication; |
|
using Microsoft.AspNetCore.Authentication.JwtBearer; |
|
using Microsoft.AspNetCore.Hosting; |
|
using Microsoft.AspNetCore.Mvc.Authorization; |
|
using Microsoft.AspNetCore.Mvc.Controllers; |
|
using Microsoft.Extensions.Configuration; |
|
using Microsoft.Extensions.DependencyInjection.Extensions; |
|
using Microsoft.IdentityModel.Tokens; |
|
using Microsoft.OpenApi.Models; |
|
using SqlSugar; |
|
using System.Data; |
|
using System.Text; |
|
using System.Text.Json.Serialization; |
|
using System.Text.Json; |
|
using Microsoft.AspNetCore.Http.Json; |
|
using _24Hour.Controllers.Common; |
|
|
|
#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Îļþ |
|
builder.Services.AddSwaggerGen(c => |
|
{ |
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); |
|
//ÔÚ½Ó¿ÚÀà¡¢·½·¨±ê¼ÇÊôÐÔ [HiddenApi]£¬¿ÉÒÔ×èÖ¹¡¾SwaggerÎĵµ¡¿Éú³É |
|
c.DocumentFilter<HiddenApiFilter>(); |
|
c.OrderActionsBy(o => o.RelativePath); |
|
var basePath = System.AppDomain.CurrentDomain.BaseDirectory;//»ñȡӦÓóÌÐòËùÔÚĿ¼£¨¾ø¶Ô£¬²»Êܹ¤×÷Ŀ¼ӰÏ죬½¨Òé²ÉÓô˷½·¨»ñȡ·¾¶£© |
|
var xmlPath = Path.Combine(basePath, "24Hour.xml"); |
|
if (File.Exists(xmlPath))//±ÜÃâûÓиÃÎļþʱ±¨´í |
|
c.IncludeXmlComments(xmlPath, true); |
|
//Ìí¼ÓJwtÑéÖ¤ÉèÖà |
|
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 |
|
|
|
builder.Services.AddMvc(config => |
|
{ |
|
config.Filters.Add(new AllowAnonymousFilter()); |
|
}); |
|
// ÅäÖÿçÓò |
|
//builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", |
|
//c => |
|
//{ |
|
// c.WithOrigins(Configuration.GetSection("UrlsConfiguration:CorUrls").Value.Split(',', StringSplitOptions.RemoveEmptyEntries)) |
|
// .AllowAnyHeader() // ÔÊÐíÈκαêÍ·(Õâ¸ö×îºÃдµ½AllowAnyMethodÉÏÃæÈ¥) |
|
// .AllowAnyMethod() // ÔÊÐíÈκη½·¨·ÃÎÊ |
|
// .SetIsOriginAllowed(o => true) // =AllowAnyOrigin() |
|
// .AllowCredentials(); |
|
//})); |
|
// Ìí¼ÓÉí·ÝÑéÖ¤·þÎñ |
|
builder.Services.AddAuthentication(options => |
|
{ |
|
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; |
|
options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401 |
|
options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403 |
|
}) |
|
.AddJwtBearer(options => |
|
{ |
|
// ÅäÖÃJWTÉí·ÝÑé֤ѡÏî |
|
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 |
|
}; |
|
|
|
//ÖØµãÔÚÓÚÕâÀÅжÏÊÇWebSocketµÄ·¾¶(https://www.cnblogs.com/fger/p/11811190.html) |
|
options.Events = new JwtBearerEvents |
|
{ |
|
OnMessageReceived = (context) => |
|
{ |
|
if (!context.HttpContext.Request.Path.HasValue) return Task.CompletedTask; |
|
//ÖØµãÔÚÓÚÕâÀÅжÏÊÇWebSocketµÄ·¾¶ |
|
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; |
|
}, |
|
|
|
//´Ë´¦ÎªÈ¨ÏÞÑé֤ʧ°Üºó´¥·¢µÄʼþ |
|
OnChallenge = context => |
|
{ |
|
//´Ë´¦´úÂëΪÖÕÖ¹.Net CoreĬÈϵķµ»ØÀàÐͺÍÊý¾Ý½á¹û£¬Õâ¸öºÜÖØÒªÅ¶£¬±ØÐë |
|
context.HandleResponse(); |
|
//×Ô¶¨Òå×Ô¼ºÏëÒª·µ»ØµÄÊý¾Ý½á¹û£¬ÎÒÕâÀïÒª·µ»ØµÄÊÇJson¶ÔÏó£¬Í¨¹ýÒýÓÃNewtonsoft.Json¿â½øÐÐת»» |
|
var payload = new { StatusCode = 0, Message = "Éí·ÝÈÏ֤ʧ°Ü£¡" }; |
|
//×Ô¶¨Òå·µ»ØµÄÊý¾ÝÀàÐÍ |
|
context.Response.ContentType = "application/json"; |
|
//×Ô¶¨Òå·µ»Ø×´Ì¬Â룬ĬÈÏΪ401 ÎÒÕâÀï¸Ä³É 200 |
|
context.Response.StatusCode = StatusCodes.Status200OK; |
|
//context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
|
//Êä³öJsonÊý¾Ý½á¹û |
|
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>(); //jwt |
|
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; |
|
}); |
|
|
|
|
|
|
|
#endregion |
|
|
|
#region APP |
|
var app = builder.Build(); |
|
|
|
// Configure the HTTP request pipeline. |
|
if (app.Environment.IsDevelopment()) |
|
{ |
|
app.UseSwagger(); |
|
app.UseSwaggerUI(); |
|
} |
|
#region websocketsÅäÖÃ |
|
app.UseWebSockets(new WebSocketOptions |
|
{ |
|
KeepAliveInterval = TimeSpan.FromMinutes(2) |
|
}); |
|
//app.UseMiddleware<WebSocketMiddleware>(); |
|
#endregion |
|
app.UseStaticFiles(); |
|
app.UseHttpsRedirection(); |
|
//·ÓÉ |
|
app.UseRouting(); |
|
app.UseAuthentication(); // ÆôÓÃÉí·ÝÑéÖ¤Öмä¼þ |
|
app.UseAuthorization(); // ÆôÓÃÊÚȨÖмä¼þ |
|
//app.MapControllers(); |
|
app.UseEndpoints(endpoints => |
|
{ |
|
endpoints.MapControllers(); |
|
}); |
|
#region swagger |
|
app.UseSwagger();// ÆôÓÃSwaggerÖмä¼þ |
|
app.UseSwaggerUI(c => |
|
{ |
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); |
|
c.RoutePrefix = string.Empty; |
|
}); |
|
#endregion |
|
app.Run(); |
|
#endregion
|
|
|