2025-01-13 21:06:59 +08:00
|
|
|
|
using Microsoft.AspNetCore.Http.Features;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
|
|
|
|
using Microsoft.OpenApi.Models;
|
|
|
|
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using YD_XinWei.Commons.MemoryCaches;
|
|
|
|
|
using YD_XinWei.Commons.Users;
|
|
|
|
|
using Newtonsoft.Json.Serialization;
|
|
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using YD_XinWei.Commons.Utils;
|
|
|
|
|
using YD_XinWei.Api.Utilities;
|
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc.Authorization;
|
|
|
|
|
using Autofac;
|
|
|
|
|
using YD_XinWei.Api.Services.Impl;
|
|
|
|
|
using YD_XinWei.Api.AutoMappers;
|
|
|
|
|
using YD_XinWei.Api.Services.Interface;
|
|
|
|
|
using YD_XinWei.Api.Context;
|
|
|
|
|
using YD_XinWei.Api.Extensions;
|
2025-01-14 14:51:07 +08:00
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using VYD_XinWei.Commons.Filters;
|
2025-01-14 16:04:33 +08:00
|
|
|
|
using Microsoft.AspNetCore.Mvc.Versioning;
|
2025-01-13 21:06:59 +08:00
|
|
|
|
|
|
|
|
|
namespace YD_XinWei.Api
|
|
|
|
|
{
|
|
|
|
|
public class Startup
|
|
|
|
|
{
|
|
|
|
|
public Startup(IConfiguration configuration)
|
|
|
|
|
{
|
|
|
|
|
Configuration = configuration;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public IConfiguration Configuration { get; }
|
|
|
|
|
private IServiceCollection Services { get; set; }
|
|
|
|
|
|
|
|
|
|
public void ConfigureServices(IServiceCollection services)
|
|
|
|
|
{
|
|
|
|
|
Services = services;
|
|
|
|
|
|
|
|
|
|
AppSettings.Init(Configuration);
|
|
|
|
|
|
|
|
|
|
string dbConnectionString = AppSettings.DbConnectionString;
|
|
|
|
|
string smartSportsString = AppSettings.SmartSportsString;
|
|
|
|
|
|
|
|
|
|
// 使用 dbConnectionString 配置数据库上下文
|
|
|
|
|
services.AddDbContextPool<UserContext>(optionsBuilder =>
|
|
|
|
|
{
|
|
|
|
|
optionsBuilder.UseSqlServer(dbConnectionString);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 配置智慧体育后台数据库上下文
|
|
|
|
|
services.AddDbContextPool<SmartSportsContext>(optionsBuilder =>
|
|
|
|
|
{
|
|
|
|
|
optionsBuilder.UseSqlServer(smartSportsString);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
services.AddSingleton<JwtHelper>();
|
|
|
|
|
services.AddScoped<IUserService, UserService>();
|
|
|
|
|
services.AddScoped<IStudentService, StudentService>();
|
|
|
|
|
services.AddScoped<IHomeWorkService, HomeWorkService>();
|
|
|
|
|
services.AddScoped<ITeacherService, TeacherService>();
|
|
|
|
|
|
2025-01-14 16:04:33 +08:00
|
|
|
|
services.AddScoped<IXinWeiService, XinWeiService>();
|
|
|
|
|
|
2025-01-13 21:06:59 +08:00
|
|
|
|
services.AddScoped<ICaching, MemoryCaching>();
|
|
|
|
|
services.AddSession();
|
|
|
|
|
services.AddMemoryCache();
|
|
|
|
|
services.AddHttpContextAccessor();
|
|
|
|
|
|
|
|
|
|
Services.AddAuthentication(options =>
|
|
|
|
|
{
|
|
|
|
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
|
})
|
|
|
|
|
.AddJwtBearer(options =>
|
|
|
|
|
{
|
|
|
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
|
|
|
{
|
|
|
|
|
SaveSigninToken = true,//保存token,后台验证token是否生效(重要)
|
|
|
|
|
ValidateIssuer = true,//是否验证Issuer
|
|
|
|
|
ValidateAudience = true,//是否验证Audience
|
|
|
|
|
ValidateLifetime = true,//是否验证失效时间
|
|
|
|
|
ValidateIssuerSigningKey = true,//是否验证SecurityKey
|
|
|
|
|
ValidAudience = AppSettings.Secret.Audience,//Audience
|
|
|
|
|
ValidIssuer = AppSettings.Secret.Issuer,//Issuer,这两项和前面签发jwt的设置一致
|
|
|
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.Secret.JWT))
|
|
|
|
|
};
|
|
|
|
|
options.Events = new JwtBearerEvents()
|
|
|
|
|
{
|
|
|
|
|
OnChallenge = context =>
|
|
|
|
|
{
|
|
|
|
|
context.HandleResponse();
|
|
|
|
|
context.Response.Clear();
|
|
|
|
|
context.Response.ContentType = "application/json";
|
|
|
|
|
context.Response.StatusCode = 401;
|
|
|
|
|
Task task = context.Response.WriteAsync(new { message = "授权未通过", status = false, code = 401 }.Serialize());
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
});
|
2025-01-14 16:04:33 +08:00
|
|
|
|
|
|
|
|
|
services.AddApiVersioning(options =>
|
|
|
|
|
{
|
|
|
|
|
// 默认情况下,API 版本是必需的,通过 URL 进行版本控制
|
|
|
|
|
options.ApiVersionReader = new UrlSegmentApiVersionReader();
|
|
|
|
|
options.ReportApiVersions = true;
|
|
|
|
|
});
|
|
|
|
|
|
2025-01-13 21:06:59 +08:00
|
|
|
|
// 全局应用认证策略
|
|
|
|
|
services.AddControllers(options =>
|
|
|
|
|
{
|
|
|
|
|
var policy = new AuthorizationPolicyBuilder()
|
|
|
|
|
.RequireAuthenticatedUser()
|
|
|
|
|
.Build();
|
|
|
|
|
options.Filters.Add(new AuthorizeFilter(policy)); // 全局应用 [Authorize]
|
2025-01-14 14:51:07 +08:00
|
|
|
|
}).AddNewtonsoftJson(options =>
|
|
|
|
|
{
|
|
|
|
|
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
|
|
|
|
|
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
|
2025-01-13 21:06:59 +08:00
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
//必须appsettings.json中配置
|
|
|
|
|
string corsUrls = Configuration["CorsUrls"];
|
|
|
|
|
if (string.IsNullOrEmpty(corsUrls))
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("请配置跨请求的前端Url");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
services.AddCors(options =>
|
|
|
|
|
{
|
|
|
|
|
options.AddDefaultPolicy(
|
|
|
|
|
builder =>
|
|
|
|
|
{
|
|
|
|
|
builder.AllowAnyOrigin()
|
|
|
|
|
.SetPreflightMaxAge(TimeSpan.FromSeconds(2520))
|
|
|
|
|
.AllowAnyHeader().AllowAnyMethod();
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
|
|
|
|
services.AddControllers(options =>
|
|
|
|
|
{
|
2025-01-14 14:51:07 +08:00
|
|
|
|
options.Filters.Add<CustomApiResponseFilter>(); // 1、通用结果
|
|
|
|
|
options.Filters.Add<ExceptionFilter>();// 2、通用异常
|
2025-01-13 21:06:59 +08:00
|
|
|
|
options.ModelBinderProviders.Insert(0, new SysUserModelBinderProvider());// 3、自定义模型绑定
|
|
|
|
|
options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
|
2025-01-14 14:51:07 +08:00
|
|
|
|
}).AddNewtonsoftJson(op =>
|
2025-01-13 21:06:59 +08:00
|
|
|
|
{
|
2025-01-14 14:51:07 +08:00
|
|
|
|
op.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
|
|
|
|
|
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
|
2025-01-13 21:06:59 +08:00
|
|
|
|
});
|
|
|
|
|
services.AddSwaggerGen(c =>
|
|
|
|
|
{
|
|
|
|
|
//分为2份接口文档
|
|
|
|
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "YD_XinWei.Api", Version = "v1", Description = "跃动小程序Api" });
|
|
|
|
|
|
|
|
|
|
string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
|
|
|
|
string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
|
|
|
|
c.IncludeXmlComments(xmlPath, true);
|
|
|
|
|
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "YD_XinWei.xml"));
|
|
|
|
|
//c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "YD_XinWei.Model.xml"));
|
|
|
|
|
|
|
|
|
|
c.DocInclusionPredicate((docName, apiDes) =>
|
|
|
|
|
{
|
|
|
|
|
if (!apiDes.TryGetMethodInfo(out MethodInfo method))
|
|
|
|
|
return false;
|
|
|
|
|
/*使用ApiExplorerSettingsAttribute里面的GroupName进行特性标识
|
|
|
|
|
* DeclaringType只能获取controller上的特性
|
|
|
|
|
* 我们这里是想以action的特性为主
|
|
|
|
|
* */
|
|
|
|
|
var version = method.DeclaringType.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName);
|
|
|
|
|
if (docName == "v1" && !version.Any())
|
|
|
|
|
return true;
|
|
|
|
|
//这里获取action的特性
|
|
|
|
|
var actionVersion = method.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName);
|
|
|
|
|
if (actionVersion.Any())
|
|
|
|
|
return actionVersion.Any(v => v == docName);
|
|
|
|
|
return version.Any(v => v == docName);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
var security = new Dictionary<string, IEnumerable<string>> { { AppSettings.Secret.Issuer, new string[] { } } };
|
|
|
|
|
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
|
|
|
|
|
{
|
|
|
|
|
Description = "JWT授权token前面需要加上字段Bearer与一个空格,如Bearer token",
|
|
|
|
|
Name = "Authorization",
|
|
|
|
|
In = ParameterLocation.Header,
|
|
|
|
|
Type = SecuritySchemeType.ApiKey,
|
|
|
|
|
BearerFormat = "JWT",
|
|
|
|
|
Scheme = "Bearer"
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
|
|
|
{
|
|
|
|
|
{
|
|
|
|
|
new OpenApiSecurityScheme
|
|
|
|
|
{
|
|
|
|
|
Reference = new OpenApiReference {
|
|
|
|
|
Type = ReferenceType.SecurityScheme,
|
|
|
|
|
Id = "Bearer"
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
new string[] { }
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
})
|
|
|
|
|
.AddControllers()
|
|
|
|
|
.ConfigureApiBehaviorOptions(options =>
|
|
|
|
|
{
|
|
|
|
|
options.SuppressConsumesConstraintForFormFileParameters = true;
|
|
|
|
|
options.SuppressInferBindingSourcesForParameters = true;
|
|
|
|
|
options.SuppressModelStateInvalidFilter = true;
|
|
|
|
|
options.SuppressMapClientErrors = true;
|
|
|
|
|
options.ClientErrorMapping[404].Link =
|
|
|
|
|
"https://*/404";
|
|
|
|
|
});
|
|
|
|
|
services.AddSignalR();
|
|
|
|
|
services.AddHttpClient();
|
|
|
|
|
|
|
|
|
|
services.AddAutoMapper(typeof(MappingProfile));
|
|
|
|
|
|
|
|
|
|
//设置文件上传大小限制
|
|
|
|
|
//设置文件上传大小限制
|
|
|
|
|
services.Configure<FormOptions>(x =>
|
|
|
|
|
{
|
|
|
|
|
x.MultipartBodyLengthLimit = 1024 * 1024 * 100;//100M
|
|
|
|
|
});
|
|
|
|
|
services.Configure<KestrelServerOptions>(options =>
|
|
|
|
|
{
|
|
|
|
|
options.Limits.MaxRequestBodySize = 1024 * 1024 * 100;//100M
|
|
|
|
|
});
|
|
|
|
|
services.Configure<IISServerOptions>(options =>
|
|
|
|
|
{
|
|
|
|
|
options.MaxRequestBodySize = 1024 * 1024 * 100;//100M
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void ConfigureContainer(ContainerBuilder builder)
|
|
|
|
|
{
|
|
|
|
|
builder.RegisterType<UserLoginContext>().InstancePerLifetimeScope();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
|
|
|
|
{
|
|
|
|
|
if (env.IsDevelopment())
|
|
|
|
|
{
|
|
|
|
|
app.UseDeveloperExceptionPage();
|
|
|
|
|
}
|
|
|
|
|
//else
|
|
|
|
|
//{
|
|
|
|
|
// app.UseQuartz(env);
|
|
|
|
|
//}
|
|
|
|
|
//app.UseMiddleware<ExceptionHandlerMiddleWare>();
|
|
|
|
|
app.UseStaticFiles().UseStaticFiles(new StaticFileOptions
|
|
|
|
|
{
|
|
|
|
|
ServeUnknownFileTypes = true
|
|
|
|
|
});
|
|
|
|
|
app.UseDefaultFiles();
|
|
|
|
|
app.UseStaticFiles();
|
|
|
|
|
//app.Use(HttpRequestMiddleware.Context);
|
|
|
|
|
|
|
|
|
|
//2021.06.27增加创建默认upload文件夹
|
|
|
|
|
//string _uploadPath = (env.ContentRootPath + "/Upload").ReplacePath();
|
|
|
|
|
|
|
|
|
|
//if (!Directory.Exists(_uploadPath))
|
|
|
|
|
//{
|
|
|
|
|
// Directory.CreateDirectory(_uploadPath);
|
|
|
|
|
//}
|
|
|
|
|
|
|
|
|
|
//app.UseStaticFiles(new StaticFileOptions()
|
|
|
|
|
//{
|
|
|
|
|
// FileProvider = new PhysicalFileProvider(
|
|
|
|
|
// Path.Combine(Directory.GetCurrentDirectory(), @"Upload")),
|
|
|
|
|
// //配置访问虚拟目录时文件夹别名
|
|
|
|
|
// RequestPath = "/Upload",
|
|
|
|
|
// OnPrepareResponse = (Microsoft.AspNetCore.StaticFiles.StaticFileResponseContext staticFile) =>
|
|
|
|
|
// {
|
|
|
|
|
// //可以在此处读取请求的信息进行权限认证
|
|
|
|
|
// // staticFile.File
|
|
|
|
|
// // staticFile.Context.Response.StatusCode;
|
|
|
|
|
// }
|
|
|
|
|
//});
|
|
|
|
|
//配置HttpContext
|
|
|
|
|
app.UseStaticHttpContext();
|
|
|
|
|
|
|
|
|
|
app.UseSwagger();
|
|
|
|
|
app.UseSwaggerUI(c =>
|
|
|
|
|
{
|
|
|
|
|
//2个下拉框选项 选择对应的文档
|
|
|
|
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "YD_XinWei.Api");
|
|
|
|
|
c.RoutePrefix = "";
|
|
|
|
|
});
|
|
|
|
|
app.UseRouting();
|
|
|
|
|
app.UseCors();
|
|
|
|
|
app.UseAuthentication();
|
|
|
|
|
app.UseAuthorization();
|
|
|
|
|
app.UseEndpoints(endpoints =>
|
|
|
|
|
{
|
|
|
|
|
endpoints.MapControllers();
|
|
|
|
|
//配置SignalR
|
|
|
|
|
//if (AppSetting.UseSignalR)
|
|
|
|
|
//{
|
|
|
|
|
// string corsUrls = Configuration["CorsUrls"];
|
|
|
|
|
|
|
|
|
|
// endpoints.MapHub<HomePageMessageHub>("/message")
|
|
|
|
|
// .RequireCors(t =>
|
|
|
|
|
// t.WithOrigins(corsUrls.Split(',')).
|
|
|
|
|
// AllowAnyMethod().
|
|
|
|
|
// AllowAnyHeader().
|
|
|
|
|
// AllowCredentials());
|
|
|
|
|
//}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Swagger注释帮助类
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class SwaggerDocTag : IDocumentFilter
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 添加附加注释
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="swaggerDoc"></param>
|
|
|
|
|
/// <param name="context"></param>
|
|
|
|
|
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
|
|
|
|
|
{
|
|
|
|
|
//添加对应的控制器描述
|
|
|
|
|
swaggerDoc.Tags = new List<OpenApiTag>
|
|
|
|
|
{
|
|
|
|
|
new OpenApiTag { Name = "Test", Description = "这是描述" },
|
|
|
|
|
//new OpenApiTag { Name = "你的控制器名字,不带Controller", Description = "控制器描述" },
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|