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.
 
 
 

286 lines
10 KiB

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using IdentityModel;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Win_in.Sfs.Scp.WebApi.EntityFrameworkCore;
using StackExchange.Redis;
using Microsoft.OpenApi.Models;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc.UI.MultiTenancy;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.AuditLogging.EntityFrameworkCore;
using Volo.Abp.Autofac;
using Volo.Abp.Caching;
using Volo.Abp.Caching.StackExchangeRedis;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.SqlServer;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.PermissionManagement.EntityFrameworkCore;
using Volo.Abp.Security.Claims;
using Volo.Abp.SettingManagement.EntityFrameworkCore;
using Volo.Abp.Swashbuckle;
using Volo.Abp.VirtualFileSystem;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Serilog;
using Serilog.Events;
using Volo.Abp.AspNetCore.Mvc;
namespace Win_in.Sfs.Scp.WebApi
{
[DependsOn(
typeof(WebApiApplicationModule),
typeof(WebApiEntityFrameworkCoreModule),
typeof(WebApiHttpApiModule),
typeof(AbpAspNetCoreMvcUiMultiTenancyModule),
typeof(AbpAutofacModule),
typeof(AbpCachingStackExchangeRedisModule),
typeof(AbpEntityFrameworkCoreSqlServerModule),
typeof(AbpAuditLoggingEntityFrameworkCoreModule),
typeof(AbpPermissionManagementEntityFrameworkCoreModule),
typeof(AbpSettingManagementEntityFrameworkCoreModule),
typeof(AbpAspNetCoreSerilogModule),
typeof(AbpSwashbuckleModule)
)]
public class WebApiHttpApiHostModule : AbpModule
{
private bool _isMultiTenancy = true;
public override void ConfigureServices(ServiceConfigurationContext context)
{
var hostingEnvironment = context.Services.GetHostingEnvironment();
var configuration = context.Services.GetConfiguration();
ConfigureDbContext();
ConfigureMultiTeancy(configuration);
ConfigureSwagger(context, configuration);
ConfigureLocalization();
ConfigureAuthentication(context, configuration);
ConfigureDistributedCache(context, hostingEnvironment, configuration);
ConfigureCors(context, configuration);
}
private static void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder
.WithOrigins(
configuration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray()
)
.WithAbpExposedHeaders()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
}
private void ConfigureDistributedCache(ServiceConfigurationContext context, IWebHostEnvironment hostingEnvironment,
IConfiguration configuration)
{
Configure<AbpDistributedCacheOptions>(options => { options.KeyPrefix = "ScpWebApi:"; });
if (!hostingEnvironment.IsDevelopment())
{
var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
context.Services
.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "WebApi-Protection-Keys");
}
}
private static void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
options.Audience = "WebApi";
});
}
private void ConfigureLocalization()
{
Configure<AbpLocalizationOptions>(options =>
{
options.Languages.Add(new LanguageInfo("en", "en", "English"));
options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
});
}
private void ConfigureSwagger(ServiceConfigurationContext context, IConfiguration configuration)
{
context.Services.AddAbpSwaggerGenWithOAuth(
configuration["AuthServer:Authority"],
new Dictionary<string, string>
{
{ "WebApi", "WebApi API" }
},
//options =>
//{
// options.SwaggerDoc("v1", new OpenApiInfo {Title = "WebApi API", Version = "v1"});
// options.DocInclusionPredicate((docName, description) => true);
// options.CustomSchemaIds(type => type.FullName);
//});
options =>
{
//遍历Swagger分组,注册SwaggerDoc
foreach (var groupName in typeof(SwaggerGroupConsts).GetFields()
.Select(f => f.GetValue(null).ToString()))
{
options.SwaggerDoc(groupName,
new OpenApiInfo { Title = $"{groupName} API", Version = groupName });
}
//根据APIExplorerSetting判断是否包含于Swagger文档当前分组
options.DocInclusionPredicate(IsIncludeInDoc);
//反射注入全部Application和Application.Contract程序集说明
GetXmlFiles().ForEach(file =>
{
options.IncludeXmlComments(file);
Log.Information(" TEST-SWAGGER PATH ==> " + file);
});
options.DocumentFilter<HiddenApiFilter>();
options.CustomSchemaIds(type => type.FullName);
});
}
private void ConfigureMultiTeancy(IConfiguration configuration)
{
_isMultiTenancy = Convert.ToBoolean(configuration["IsMultiTenancy"]);
Configure<AbpMultiTenancyOptions>(options => { options.IsEnabled = _isMultiTenancy; });
}
private void ConfigureDbContext()
{
Configure<AbpDbContextOptions>(options => { options.UseSqlServer(); });
}
/// <summary>
/// 判断是否应该加入当前分组
/// </summary>
/// <param name="docName"></param>
/// <param name="apiDesc"></param>
/// <returns></returns>
private bool IsIncludeInDoc(string docName, ApiDescription apiDesc)
{
if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
{
return false;
}
var groups = methodInfo.ReflectedType.GetCustomAttributes(true)
.OfType<ApiExplorerSettingsAttribute>()
.Select(attr => attr.GroupName)
.ToList();
if (docName == SwaggerGroupConsts.Default)
{
if (groups.Count == 0)
{
return true;
}
return apiDesc.GroupName == SwaggerGroupConsts.Default;
}
return docName == apiDesc.GroupName;
}
/// <summary>
/// 获取当前目录下的xml文档
/// </summary>
/// <returns></returns>
private List<string> GetXmlFiles()
{
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
Log.Information(" TEST- base Path PATH ==> " + basePath);
//Console.WriteLine(" TEST- base Path PATH ==> " + basePath);
var files1 = Directory.GetFiles(basePath, "*.Application*.xml");
return files1.ToList();
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
var env = context.GetEnvironment();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseErrorPage();
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseCorrelationId();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
if (_isMultiTenancy)
{
app.UseMultiTenancy();
}
app.UseAbpRequestLocalization();
app.UseAuthorization();
app.UseSwagger();
app.UseAbpSwaggerUI(options =>
{
//options.SwaggerEndpoint("/swagger/v1/swagger.json", "Support APP API");
//遍历Swagger分组,注册SwaggerEndpoint
foreach (var groupName in typeof(SwaggerGroupConsts).GetFields()
.Select(f => f.GetValue(null).ToString()))
{
Log.Information(groupName);
options.SwaggerEndpoint($"/swagger/{groupName}/swagger.json", $"{groupName} API");
}
var configuration = context.GetConfiguration();
options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
options.OAuthScopes("WebApi");
});
app.UseAuditing();
app.UseAbpSerilogEnrichers();
app.UseConfiguredEndpoints();
}
}
}