Skip to content

Commit b739260

Browse files
committed
WebApi v0.2.6 添加 WebApiEngineOptions
1 parent 19ebf53 commit b739260

File tree

10 files changed

+7305
-68
lines changed

10 files changed

+7305
-68
lines changed

Sample/Senparc.CO2NET.Sample.net6/Startup.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,17 @@ public void ConfigureServices(IServiceCollection services)
5757
WebApi.Register.AdditionalMethods.Add(typeof(EncryptHelper).GetMethod("GetMD5", new[] { typeof(string), typeof(string) }), "Additional");
5858

5959
var docXmlPath = Path.Combine(WebHostEnvironment.ContentRootPath, "App_Data", "ApiDocXml");
60-
services.AddAndInitDynamicApi(builder, docXmlPath, ApiRequestMethod.Get, null, 400, false, true, m => null, forbiddenExternalAccess: true);
60+
services.AddAndInitDynamicApi(builder, options =>
61+
{
62+
options.DocXmlPath = docXmlPath;
63+
options.DefaultRequestMethod = ApiRequestMethod.Get;
64+
options.BaseApiControllerType = null;
65+
options.CopyCustomAttributes = true;
66+
options.TaskCount = Environment.ProcessorCount * 4;
67+
options.ShowDetailApiLog = true;
68+
options.AdditionalAttributeFunc = null;
69+
options.ForbiddenExternalAccess = true;
70+
});
6171

6272
#endregion
6373

src/Senparc.CO2NET.Tests/Helpers/Strings/EncryptHelperTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,9 @@ public void AESEncryptTest()
115115
[TestMethod]
116116
public void AESEncryptForTenpayV3Test()
117117
{
118-
var key = "TheKey";
118+
var key = "TheKey";//换成你自己的 Key,否则通不过
119119
{
120-
//TenPayV3(旧)中的 req_info
120+
//TenPayV3(旧)中的 req_info,换成你自己的 req_info,否则通不过
121121
var input = "6scm3lyoIZj2YLSVosQsd7xziXw9vJb9w9A5jY0LUNM0O5g9T3MoNgJ5A2xXD26M44rPjGsQXLYxIIxMJWWLPmdXef0xq+b1XKMaKA49H/ft1+82bKPNQS9dYK7RBQ6cvfFjBJMrSvseyWE5ASGfMLg9psnMdU1sC7DMSRSxMRrw7Vzkuvu2QWbK1SA26fehtqHphKoW1pZNy7fDnQb3j+vUeZTDhzbc2g0kspo9JQS60p0L79Aj9Gl15OTreXEplMi4nAU/E4ULptjtF+ylicF0pHKmjsjMufSxYnaBaGZmLlioaigZt1RTWBO90D2NmodFCm7muyGcuCbdfvLhB6Yde8KfVM/yhnC0b42iwi0ASwjCA+jlVIm9ys6Wxrz1lSAXcRF06+ySXgGRXBMpdIitW59Hx4zS0UIATXes9U1TDaZXGYrZDZM02GkqYAX4KiqpmhKC+PNtGrtbPNZbwWWtSl+UE6h4QyPv2cPdRPRMyGlzabauriMiNALF8bDaNTn6K1Nf3tA3nKWh1oemvjCYvT9+mUI8jnyEsXVjnakCOJyKoCIzNgJwliUIV4GXPIauWPFbbG3Tbtm8AAv3FC1yAvdustwLreiXOvOXgvZnSXIV4xLgUfjFWzoc9crwMXd8gJJFW0YAjhF+78WJ4yvDklg/oZnlXUo/ZEnjRdM2AxVTaAHuVNyi3tGMBDustRotkLbAKlR/GW/GaQRF0t8fagJJrEvbOkyrA+NUTCTHOpJ2Yi4YWoj9M2Zar4cXkKixOkx+PpgKMgMffOEnFAe1oTxI8ZwOrxgAjN8O9kPoXecQ2TaP4OyN/4vNxMZMjM/ksmSgAilvEj91PYLme4MY5WjUunLQxdiNx2ZgJj4+b1xyN+thQaYjN34XM97Ao7xZxVlexxN3SspOUvtKQ9Wn3T6c9UAgl184yNYrV/ZJ2xWwpeVyL1H/h29tQxxBjg1SIA1wLda3fRvWIszpqL5OWVUMzQztE4egmVuU8txrMkAEqOhFE1cdzIm7GFJL08IZnMslEs0em/+tJIw8igmQvihNrKwgtDbR78Lsrv84Tpll9qL76PqLrgqaYQuU";
122122

123123
var md5Str = EncryptHelper.GetLowerMD5(key, Encoding.UTF8);

src/Senparc.CO2NET.WebApi.Tests/App_Data/ApiDocXml/DynamicFiles/Senparc.DynamicWebApi.WeChat_OfficialAccount.xml

Lines changed: 7173 additions & 0 deletions
Large diffs are not rendered by default.

src/Senparc.CO2NET.WebApi.Tests/WebApiEngines/BaseApiControllerTypeTests.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ public void BaseTypeTest()
1919
base.Init();//初始化
2020

2121
var appDataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "App_Data");// ServerUtility.ContentRootMapPath("~/App_Data");
22-
base.ServiceCollection.AddAndInitDynamicApi(MvcCoreBuilder, appDataPath, taskCount: 400);
22+
base.ServiceCollection.AddAndInitDynamicApi(MvcCoreBuilder, options =>
23+
{
24+
options.DocXmlPath = appDataPath;
25+
options.TaskCount = 400;
26+
});
2327

2428
{
2529
var assembly = WebApiEngine.ApiAssemblyCollection.First(z => z.Key == "BaseApiControllerTypeTest").Value;

src/Senparc.CO2NET.WebApi.Tests/WebApiEngines/WebApiEngineTests.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,11 @@ public void InitDynamicApiTest()
2424
var findWeixinApiService = ServiceProvider.GetService<FindApiService>();
2525
var docXmlPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\", "App_Data","ApiDocXml"));// ServerUtility.ContentRootMapPath("~/App_Data");
2626
Console.WriteLine("Test docXmlPath:" + docXmlPath);
27-
base.ServiceCollection.AddAndInitDynamicApi(MvcCoreBuilder, docXmlPath, taskCount: 400);
27+
base.ServiceCollection.AddAndInitDynamicApi(MvcCoreBuilder, options =>
28+
{
29+
options.DocXmlPath = docXmlPath;
30+
options.TaskCount = 400;
31+
});
2832
}
2933
}
3034

src/Senparc.CO2NET.WebApi/Senparc.CO2NET.WebApi.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
33
<TargetFrameworks>netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
4-
<Version>0.2.5.9-preview3</Version>
4+
<Version>0.2.6-preview3</Version>
55
<LangVersion>latest</LangVersion>
66
<AssemblyName>Senparc.CO2NET.WebApi</AssemblyName>
77
<RootNamespace>Senparc.CO2NET.WebApi</RootNamespace>
@@ -28,6 +28,7 @@
2828
v0.2.4 添加可额外注入的类或方法
2929
v0.2.5 优化异步线程执行
3030
v0.2.5.7 添加 ForbiddenExternalAccess 参数,设置是否允许外部访问
31+
v0.2.6 添加 WebApiEngineOptions
3132
</PackageReleaseNotes>
3233
</PropertyGroup>
3334
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">

src/Senparc.CO2NET.WebApi/WebApiEngines/WebApiEngine.Doc.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ private async Task<ApiXmlInfo> TryGetApiXmlInfo(string category, string sourceAs
176176
if (!sourceApiXmlCollection.ContainsKey(sourceAssemblyName))
177177
{
178178
var xmlFileName = $"{sourceAssemblyName}.xml";//XML 文件名
179-
var xmlFilePath = Path.Combine(_docXmlPath, xmlFileName);
179+
var xmlFilePath = Path.Combine(DocXmlPath, xmlFileName);
180180
if (File.Exists(xmlFilePath))
181181
{
182182
apiXmlInfo = new();
@@ -289,7 +289,7 @@ internal void SaveDynamicApiXml()
289289
return;
290290
}
291291

292-
var dynamicFilePath = GetDynamicFilePath(_docXmlPath);
292+
var dynamicFilePath = GetDynamicFilePath(DocXmlPath);
293293
if (!Directory.Exists(dynamicFilePath))
294294
{
295295
Directory.CreateDirectory(dynamicFilePath);

src/Senparc.CO2NET.WebApi/WebApiEngines/WebApiEngine.cs

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -43,37 +43,38 @@ public partial class WebApiEngine
4343

4444
public static string GetDynamicFilePath(string apiXmlPath) => Path.Combine(apiXmlPath, "DynamicFiles");
4545

46-
private string _docXmlPath;
46+
internal string DocXmlPath { get; set; }
47+
internal int TaskCount { get; set; }
48+
4749
private bool _showDetailApiLog = false;
4850
private readonly Lazy<FindApiService> _findWeixinApiService;
4951
private readonly ApiRequestMethod _defaultRequestMethod;
5052
private readonly bool _copyCustomAttributes;
51-
private int _taskCount;
5253
private Type _typeOfApiBind = typeof(ApiBindAttribute);
5354
private Type _baseApiControllerType;
5455

55-
public bool BuildXml => _docXmlPath != null;
56+
public bool BuildXml => DocXmlPath != null;
5657

5758
/// <summary>
5859
/// WebApiEngine
5960
/// </summary>
60-
/// <param name="defaultRequestMethod">默认请求方式</param>
61-
/// <param name="baseApiControllerType">全局 ApiController 的基类,默认为 ControllerBase</param>
62-
/// <param name="taskCount">同时执行线程数</param>
63-
/// <param name="showDetailApiLog"></param>
64-
/// <param name="copyCustomAttributes"></param>
65-
/// <param name="defaultAction">默认请求类型,如 Post,Get</param>
66-
/// <param name="forbiddenExternalAccess">是否允许外部访问,默认为 false,只允许本机访问自动生成的 WebApi</param>
67-
public WebApiEngine(string docXmlPath, ApiRequestMethod defaultRequestMethod = ApiRequestMethod.Post, Type baseApiControllerType = null, bool copyCustomAttributes = true, int taskCount = 4, bool showDetailApiLog = false, bool forbiddenExternalAccess = true)
61+
/// <param name="options"> WebApiEngine 配置</param>
62+
public WebApiEngine(Action<WebApiEngineOptions> options = null)
6863
{
69-
_docXmlPath = docXmlPath;
64+
WebApiEngineOptions opt = new();
65+
options?.Invoke(opt);
66+
67+
_ = opt.DefaultRequestMethod == ApiRequestMethod.GlobalDefault ? throw new Exception($"{nameof(opt.DefaultRequestMethod)} 不能作为默认请求类型!") : true;
68+
69+
DocXmlPath = opt.DocXmlPath;
7070
_findWeixinApiService = new Lazy<FindApiService>(new FindApiService());
71-
_defaultRequestMethod = defaultRequestMethod;
72-
_baseApiControllerType = baseApiControllerType ?? typeof(ControllerBase);
73-
_copyCustomAttributes = copyCustomAttributes;
74-
_taskCount = taskCount;
75-
_showDetailApiLog = showDetailApiLog;
76-
Register.ForbiddenExternalAccess = forbiddenExternalAccess;
71+
_defaultRequestMethod = opt.DefaultRequestMethod;
72+
_baseApiControllerType = opt.BaseApiControllerType ?? typeof(ControllerBase);
73+
_copyCustomAttributes = opt.CopyCustomAttributes;
74+
TaskCount = opt.TaskCount;
75+
_showDetailApiLog = opt.ShowDetailApiLog;
76+
Register.ForbiddenExternalAccess = opt.ForbiddenExternalAccess;
77+
WebApiEngine.AdditionalAttributeFunc = opt.AdditionalAttributeFunc;
7778
}
7879

7980
/// <summary>
@@ -151,10 +152,10 @@ public async Task<int> BuildWebApi(IGrouping<string, KeyValuePair<string, ApiBin
151152

152153
//预分配每个线程需要领取的任务(索引范围)
153154
var apiFilterMaxIndex = apiBindFilterList.Length - 1;//最大索引
154-
var avgBlockCount = (int)((apiBindFilterList.Length - 1) / _taskCount);//每个线程(块)领取的平均数量
155+
var avgBlockCount = (int)((apiBindFilterList.Length - 1) / TaskCount);//每个线程(块)领取的平均数量
155156
var lastEndIndex = -1;//上一个块的结束索引
156157

157-
for (int taskIndex = 0; taskIndex < _taskCount; taskIndex++)
158+
for (int taskIndex = 0; taskIndex < TaskCount; taskIndex++)
158159
{
159160
if (lastEndIndex >= apiFilterMaxIndex)
160161
{
@@ -163,7 +164,7 @@ public async Task<int> BuildWebApi(IGrouping<string, KeyValuePair<string, ApiBin
163164

164165
var blockStart = Math.Min(lastEndIndex + 1, apiFilterMaxIndex);//当前块起始索引
165166
var blockEnd = 0;//当前快结束索引
166-
if (taskIndex == _taskCount - 1 || /*最后一个快,一直分配到最后(解决余数问题)*/
167+
if (taskIndex == TaskCount - 1 || /*最后一个快,一直分配到最后(解决余数问题)*/
167168
avgBlockCount == 0 /*如果API总数比线程数还要少,则只够一个模块*/)
168169
{
169170
blockEnd = apiFilterMaxIndex;//

src/Senparc.CO2NET.WebApi/WebApiEngines/WebApiEngineExtensions.cs

Lines changed: 15 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Options;
23
using Senparc.CO2NET.ApiBind;
34
using Senparc.CO2NET.Trace;
45
using System;
@@ -22,18 +23,10 @@ public static class WebApiEngineExtensions
2223
/// <param name="docXmlPath">XML 文档文件夹路径,如果传入 null,则不自动生成 XML 说明文件</param>
2324
/// <param name="builder"></param>
2425
/// <param name="services"></param>
25-
/// <param name="defaultRequestMethod">默认请求方式</param>
26-
/// <param name="baseApiControllerType">全局 ApiController 的基类,默认为 ControllerBase</param>
27-
/// <param name="showDetailApiLog"></param>
28-
/// <param name="taskCount"></param>
29-
/// <param name="additionalAttributes"></param>
30-
/// <param name="buildXml">是否创建动态 API 对应的 XML 注释文件</param>
31-
/// <param name="additionalAttributeFunc">是否复制自定义特性(AppBindAttribute 除外)</param>
32-
/// <param name="forbiddenExternalAccess">是否允许外部访问,默认为 false,只允许本机访问相关 API</param>
33-
public static void AddAndInitDynamicApi(this IServiceCollection services, IMvcCoreBuilder builder,
34-
string docXmlPath, ApiRequestMethod defaultRequestMethod = ApiRequestMethod.Post, Type baseApiControllerType = null, int taskCount = 4, bool showDetailApiLog = false, bool copyCustomAttributes = true, Func<MethodInfo, IEnumerable<CustomAttributeBuilder>> additionalAttributeFunc = null, bool forbiddenExternalAccess = true)
26+
/// <param name="options"> WebApiEngine 配置</param>
27+
public static void AddAndInitDynamicApi(this IServiceCollection services, IMvcCoreBuilder builder, Action<WebApiEngineOptions> options = null)
3528
{
36-
AddAndInitDynamicApi(services, (builder, null), docXmlPath, defaultRequestMethod, baseApiControllerType, taskCount, showDetailApiLog, copyCustomAttributes, additionalAttributeFunc, forbiddenExternalAccess);
29+
AddAndInitDynamicApi(services, (builder, null), options);
3730
}
3831

3932

@@ -43,17 +36,10 @@ public static void AddAndInitDynamicApi(this IServiceCollection services, IMvcCo
4336
/// <param name="docXmlPath">App_Data 文件夹路径</param>
4437
/// <param name="builder"></param>
4538
/// <param name="services"></param>
46-
/// <param name="defaultRequestMethod">默认请求方式</param>
47-
/// <param name="baseApiControllerType">全局 ApiController 的基类,默认为 ControllerBase</param>
48-
/// <param name="showDetailApiLog"></param>
49-
/// <param name="taskCount"></param>
50-
/// <param name="additionalAttributes"></param>
51-
/// <param name="additionalAttributeFunc">是否复制自定义特性(AppBindAttribute 除外)</param>
52-
/// <param name="forbiddenExternalAccess">是否允许外部访问,默认为 false,只允许本机访问相关 API</param>
53-
public static void AddAndInitDynamicApi(this IServiceCollection services, IMvcBuilder builder,
54-
string docXmlPath, ApiRequestMethod defaultRequestMethod = ApiRequestMethod.Post, Type baseApiControllerType = null, int taskCount = 4, bool showDetailApiLog = false, bool copyCustomAttributes = true, Func<MethodInfo, IEnumerable<CustomAttributeBuilder>> additionalAttributeFunc = null, bool forbiddenExternalAccess = true)
39+
/// <param name="options"> WebApiEngine 配置</param>
40+
public static void AddAndInitDynamicApi(this IServiceCollection services, IMvcBuilder builder, Action<WebApiEngineOptions> options = null)
5541
{
56-
AddAndInitDynamicApi(services, (null, builder), docXmlPath, defaultRequestMethod, baseApiControllerType, taskCount, showDetailApiLog, copyCustomAttributes, additionalAttributeFunc, forbiddenExternalAccess);
42+
AddAndInitDynamicApi(services, (null, builder), options);
5743
}
5844

5945
/// <summary>
@@ -62,25 +48,15 @@ public static void AddAndInitDynamicApi(this IServiceCollection services, IMvcBu
6248
/// <param name="docXmlPath">App_Data 文件夹路径</param>
6349
/// <param name="builder"></param>
6450
/// <param name="services"></param>
65-
/// <param name="defaultRequestMethod">默认请求方式</param>
66-
/// <param name="baseApiControllerType">全局 ApiController 的基类,默认为 ControllerBase</param>
67-
/// <param name="showDetailApiLog"></param>
68-
/// <param name="taskCount"></param>
69-
/// <param name="additionalAttributes"></param>
70-
/// <param name="additionalAttributeFunc">是否复制自定义特性(AppBindAttribute 除外)</param>
71-
/// <param name="forbiddenExternalAccess">是否允许外部访问,默认为 false,只允许本机访问相关 API</param>
72-
private static void AddAndInitDynamicApi(this IServiceCollection services, (IMvcCoreBuilder coreBuilder, IMvcBuilder builder) builder,
73-
string docXmlPath, ApiRequestMethod defaultRequestMethod = ApiRequestMethod.Post, Type baseApiControllerType = null,
74-
int taskCount = 4, bool showDetailApiLog = false, bool copyCustomAttributes = true, Func<MethodInfo, IEnumerable<CustomAttributeBuilder>> additionalAttributeFunc = null, bool forbiddenExternalAccess = true)
51+
/// <param name="options"> WebApiEngine 配置</param>
52+
private static void AddAndInitDynamicApi(this IServiceCollection services,
53+
(IMvcCoreBuilder coreBuilder, IMvcBuilder builder) builder,
54+
Action<WebApiEngineOptions> options = null)
7555
{
76-
_ = defaultRequestMethod != ApiRequestMethod.GlobalDefault ? true : throw new Exception($"{nameof(defaultRequestMethod)} 不能作为默认请求类型!");
77-
7856
services.AddScoped<FindApiService>();
79-
services.AddScoped(s => new WebApiEngine(docXmlPath));
80-
81-
WebApiEngine.AdditionalAttributeFunc = additionalAttributeFunc;
57+
services.AddScoped(s => new WebApiEngine(options));
8258

83-
var webApiEngine = new WebApiEngine(docXmlPath, defaultRequestMethod, baseApiControllerType, copyCustomAttributes, taskCount, showDetailApiLog, forbiddenExternalAccess);
59+
var webApiEngine = new WebApiEngine(options);
8460

8561
bool preLoad = true;
8662

@@ -90,7 +66,7 @@ private static void AddAndInitDynamicApi(this IServiceCollection services, (IMvc
9066
//确保目录存在
9167
if (webApiEngine.BuildXml)
9268
{
93-
webApiEngine.TryCreateDir(docXmlPath);
69+
webApiEngine.TryCreateDir(webApiEngine.DocXmlPath);
9470
}
9571

9672
var dt1 = SystemTime.Now;
@@ -170,7 +146,7 @@ private static void AddAndInitDynamicApi(this IServiceCollection services, (IMvc
170146
webApiEngine.WriteLog(new string('=', 80));
171147
var totalApi = assemblyBuildStat.Values.Sum(z => z.apiCount);
172148
webApiEngine.WriteLog(string.Format("{0,25} | {1,15}| {2,15} |{3,15}", $"Total", $"API Count:{totalApi}", $"Cost:{totalCost}ms", $""));
173-
webApiEngine.WriteLog($"Total Average Cost: {Math.Round(totalCost / totalApi, 4)} ms \t\tTask Count: {taskCount}");
149+
webApiEngine.WriteLog($"Total Average Cost: {Math.Round(totalCost / totalApi, 4)} ms \t\tTask Count: {webApiEngine.TaskCount}");
174150
webApiEngine.WriteLog("");
175151

176152
#endregion

0 commit comments

Comments
 (0)