203 lines
8.1 KiB
C#
Executable File
203 lines
8.1 KiB
C#
Executable File
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Http.Features;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.FileProviders;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using Newtonsoft.Json.Serialization;
|
|
using Opsoft.NetCore.O3App.Infrastructure;
|
|
using Opsoft.NetCore.O3App.Shared;
|
|
using Opsoft.NetCore.O3App.Shared.Extensions;
|
|
using Opsoft.NetCore.O3App.WebApi.Extensions;
|
|
using Opsoft.NetCore.O3App.WebApi.Model;
|
|
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
namespace Opsoft.NetCore.O3App.WebApi
|
|
{
|
|
public class Startup
|
|
{
|
|
private IServiceCollection _services;
|
|
public IConfiguration Configuration { get; }
|
|
|
|
public Startup(IConfiguration configuration)
|
|
{
|
|
Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
|
|
}
|
|
|
|
public void ConfigureServices(IServiceCollection services)
|
|
{
|
|
//后面配置为 所有 控制器转 Json 时不改变 属性的 大小写
|
|
services.AddControllers().AddJsonOptions(opt => { opt.JsonSerializerOptions.PropertyNamingPolicy = null; });
|
|
services.Configure<FormOptions>(options =>
|
|
{
|
|
// Set the limit to 256 MB
|
|
options.MultipartBodyLengthLimit = 1024 * 1024 * 2000;
|
|
options.MultipartHeadersCountLimit = 10;
|
|
});
|
|
//Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead
|
|
services.Configure<KestrelServerOptions>(options =>
|
|
{
|
|
options.AllowSynchronousIO = true;
|
|
});
|
|
services.Configure<IISServerOptions>(options =>
|
|
{
|
|
options.AllowSynchronousIO = true;
|
|
});
|
|
|
|
services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
|
|
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
|
|
services.AddAuthentication(opt =>
|
|
{
|
|
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
})
|
|
.AddJwtBearer(con =>
|
|
{
|
|
con.RequireHttpsMetadata = false;
|
|
con.SaveToken = true;
|
|
con.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
|
|
ValidIssuer = token.Issuer,
|
|
ValidAudience = token.Audience,
|
|
ValidateIssuer = false,
|
|
ValidateAudience = false
|
|
};
|
|
});
|
|
services.AddCors(options =>
|
|
{
|
|
options.AddPolicy("any", builder =>
|
|
{
|
|
builder.AllowAnyMethod()
|
|
.SetIsOriginAllowed(_ => true)
|
|
.AllowAnyHeader()
|
|
.AllowCredentials();
|
|
});
|
|
});
|
|
services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = false);
|
|
services
|
|
.AddOptions()
|
|
.AddLogging(config => config.AddConfiguration(Configuration.GetSection("Logging")).AddConsole().AddDebug())
|
|
.AddHttpClient()
|
|
.AddCustomHttpClient()
|
|
.AddSkynetLogger()
|
|
.AddTraceId()
|
|
.AddMvc(opt =>
|
|
{
|
|
opt.UseCentralRoutePrefix(new RouteAttribute("O3/v1/[controller]/[action]"));
|
|
opt.Filters.Add<GlobalExceptionFilterAttribute>();
|
|
opt.Filters.Add<ResultConvertFilterAttribute>();
|
|
})
|
|
.AddNewtonsoftJson(options =>
|
|
{
|
|
options.SerializerSettings.DateFormatString = Constants.DateTimeFormats.DateTime;
|
|
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
|
|
});
|
|
|
|
services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
|
|
services.AddScoped<IUserService, UserService>();
|
|
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
|
//services.AddSwaggerGen(c =>
|
|
// {
|
|
// c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "O3App API", Version = "v1" });
|
|
// c.CustomSchemaIds(s => s.FullName);
|
|
// });
|
|
|
|
#region 缓存处理
|
|
//启用MemoryCache缓存
|
|
/*基础数据部分缓存时间为20分钟
|
|
*汇报的数据默认添加60分钟的缓存
|
|
*/
|
|
services.AddMemoryCache();
|
|
#endregion
|
|
|
|
_services = services;
|
|
}
|
|
|
|
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
|
{
|
|
ListAllRegisteredServices(app);
|
|
app.UseTraceId();
|
|
|
|
if (env.IsDevelopment())
|
|
{
|
|
app.UseDeveloperExceptionPage();
|
|
}
|
|
|
|
//配置HttpContext
|
|
app.UseStaticHttpContext();
|
|
app.UseMiddleware(typeof(CustomResponseHeaderMiddleware));
|
|
//app.UseSwagger();
|
|
//app.UseSwaggerUI(c =>
|
|
//{
|
|
// c.SwaggerEndpoint("/swagger/v1/swagger.json", "O3App API V1");
|
|
// c.RoutePrefix = string.Empty;
|
|
//});
|
|
|
|
//启用验证
|
|
app.UseAuthentication();
|
|
|
|
app.UsePathBase(new PathString(Constants.RoutePrefix));
|
|
app.UseRouting();
|
|
|
|
app.UseCors("any");
|
|
//app.UseHttpsRedirection();
|
|
app.UseAuthorization();
|
|
|
|
app.UseStaticFiles(new StaticFileOptions
|
|
{
|
|
ServeUnknownFileTypes = true,
|
|
FileProvider = new PhysicalFileProvider(
|
|
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),//wwwroot相当于真实目录
|
|
RequestPath = new PathString("/src") //src相当于别名,为了安全
|
|
});
|
|
app.UseDirectoryBrowser();
|
|
|
|
app.UseEndpoints(endpoints =>
|
|
{
|
|
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Service}/{action=Index}");
|
|
});
|
|
|
|
app.Use(next => new RequestDelegate(
|
|
async context =>
|
|
{
|
|
context.Request.EnableBuffering();
|
|
await next(context);
|
|
}
|
|
));
|
|
|
|
}
|
|
|
|
private void ListAllRegisteredServices(IApplicationBuilder app)
|
|
{
|
|
app.Map($"{Constants.RoutePrefix}/allservices", builder => builder.Run(async context =>
|
|
{
|
|
var sb = new StringBuilder();
|
|
sb.Append("<h1>All Services</h1>");
|
|
sb.Append("<table><thead>");
|
|
sb.Append("<tr><th>Type</th><th>Lifetime</th><th>Instance</th></tr>");
|
|
sb.Append("</thead><tbody>");
|
|
foreach (var svc in _services)
|
|
{
|
|
sb.Append("<tr>");
|
|
sb.Append($"<td>{svc.ServiceType.FullName}</td>");
|
|
sb.Append($"<td>{svc.Lifetime}</td>");
|
|
sb.Append($"<td>{svc.ImplementationType?.FullName}</td>");
|
|
sb.Append("</tr>");
|
|
}
|
|
sb.Append("</tbody></table>");
|
|
await context.Response.WriteAsync(sb.ToString());
|
|
}));
|
|
}
|
|
}
|
|
} |