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
12 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 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();
_isMultiTenancy = Convert.ToBoolean(configuration["IsMultiTenancy"]);
Configure<AbpDbContextOptions>(options =>
{
options.UseSqlServer();
});
Configure<AbpMultiTenancyOptions>(options =>
{
options.IsEnabled = _isMultiTenancy;
});
if (hostingEnvironment.IsDevelopment())
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
options.FileSets.ReplaceEmbeddedByPhysical<WebApiDomainSharedModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Win_in.Sfs.Scp.WebApi.Domain.Shared", Path.DirectorySeparatorChar)));
options.FileSets.ReplaceEmbeddedByPhysical<WebApiDomainModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Win_in.Sfs.Scp.WebApi.Domain", Path.DirectorySeparatorChar)));
options.FileSets.ReplaceEmbeddedByPhysical<WebApiApplicationContractsModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Win_in.Sfs.Scp.WebApi.Application.Contracts", Path.DirectorySeparatorChar)));
options.FileSets.ReplaceEmbeddedByPhysical<WebApiApplicationModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Win_in.Sfs.Scp.WebApi.Application", Path.DirectorySeparatorChar)));
});
}
Configure<AbpAspNetCoreMvcOptions>(options =>
{
options
.ConventionalControllers
.Create(typeof(WebApiApplicationModule).Assembly);
});
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.CustomSchemaIds(type => type.FullName);
});
Configure<AbpLocalizationOptions>(options =>
{
options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
options.Languages.Add(new LanguageInfo("en", "en", "English"));
options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish"));
options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi", "in"));
options.Languages.Add(new LanguageInfo("it", "it", "Italian", "it"));
options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak"));
options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
});
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
options.Audience = "WebApi";
});
Configure<AbpDistributedCacheOptions>(options =>
{
options.KeyPrefix = "WebApi:";
});
if (!hostingEnvironment.IsDevelopment())
{
var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
context.Services
.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "WebApi-Protection-Keys");
}
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();
});
});
}
/// <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();
}
}
}