-
Notifications
You must be signed in to change notification settings - Fork 3
/
~DemoModular.cs
214 lines (172 loc) · 7.96 KB
/
~DemoModular.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using Biwen.QuickApi.DemoWeb.Apis.Endpoints;
using Biwen.QuickApi.DemoWeb.Components;
using Biwen.QuickApi.DemoWeb.Schedules;
using Biwen.QuickApi.FeatureManagement;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Options;
using Microsoft.FeatureManagement.Mvc;
using Constants = Biwen.QuickApi.FeatureManagement.Constants;
namespace Biwen.QuickApi.DemoWeb
{
/// <summary>
/// 前置的模块
/// </summary>
public class PreModular1 : ModularBase
{
public override void ConfigureServices(IServiceCollection services)
{
// Add ScheduleTaskStore
services.AddScheduleMetadataStore<DemoStore>();
services.ConfigureQuickApiFeatureManagementOptions(o =>
{
//自定义特性管理模块的返回状态码
o.StatusCode = StatusCodes.Status405MethodNotAllowed;
//自定义特性管理模块的错误处理
//o.OnErrorAsync = ctx =>
//{
// ctx.Response.WriteAsync(o.StatusCode.ToString());
//};
});
//在前置模块配置DemoOptions,DemoModular就中可以直接注入
services.AddOptions<DemoOptions>().Configure(c =>
{
c.Name += "!!!!";
c.Enable = true;
});
}
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
base.Configure(app, routes, serviceProvider);
}
}
/// <summary>
/// Demo模块
/// </summary>
/// <param name="environment"></param>
[PreModular<PreModular1>]
public class DemoModular(IHostEnvironment environment, IOptions<DemoOptions> options) : ModularBase
{
public override int Order => Constants.Order + 1;
/// <summary>
/// 请注意,如果需要在模块中使用配置,请使用构造函数注入,且需要在前置模块中配置!
/// 当然你也可以直接注入IConfiguration获取.
/// </summary>
public DemoOptions Options { get; } = options.Value;
/// <summary>
/// 测试模块仅用于开发测试
/// </summary>
public override Func<bool> IsEnable => () => options.Value.Enable; //environment.IsDevelopment();
public override void ConfigureServices(IServiceCollection services)
{
//hybrid cache NET9 新功能,多级缓存避免分布式缓存的强制转换,需要引用Microsoft.Extensions.Caching.Hybri
services.AddHybridCache(options =>
{
options.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromSeconds(5 * 60),//默认5分钟缓存
LocalCacheExpiration = TimeSpan.FromSeconds(5 * 60 - 1)//本地缓存提前1秒过期
};
});
// Add services to the container.
//services.AddScoped<HelloService>();
services.AddAutoInject();
// keyed services
//builder.Services.AddKeyedScoped<HelloService>("hello");
}
/// <summary>
/// 模拟的缓存数据类型
/// </summary>
/// <param name="DateTime"></param>
public record CacheData(DateTime? DateTime);
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
routes.MapGroup("root", x =>
{
x.MapGet("/binder", (HttpContext context, BindRequest request) =>
{
//测试默认绑定器
return Results.Content(request.Hello);
});
//测试HtmlSanitizer
x.MapGet("/xss", () => { return "<a href=\"javascript: alert('xss')\">Click me</a>".SanitizeHtml(); });
x.MapGet("/outputcache/{id:int?}", (int? id) =>
{
return Results.Content($"{id}-{DateTime.Now}");
}).CacheOutput(policy =>
{
//缓存10s过期
policy.Expire(TimeSpan.FromSeconds(10d));
});
//分布式缓存,性能不佳,建议使用.NET9新增hybrid缓存
x.MapGet("/cached-in-distribute", async (IDistributedCache distributedCache) =>
{
if (await distributedCache.GetStringAsync("$cached-in-memory") is null)
{
var data = System.Text.Json.JsonSerializer.Serialize(new CacheData(DateTime.Now));
await distributedCache.SetStringAsync("$cached-in-memory", data, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10d)
});
}
var fromCacheData = System.Text.Json.JsonSerializer.Deserialize<CacheData>(
await distributedCache.GetStringAsync("$cached-in-memory") ?? throw new Exception());
return Results.Content($"{fromCacheData?.DateTime}-{DateTime.Now}");
}).WithDescription("分布式缓存,存在序列化&反序列化,性能较差");
//hybrid缓存,避免分布式缓存的强制转换
x.MapGet("/cached-in-hybrid", async (HybridCache hybridCache) =>
{
var cachedDate = await hybridCache.GetOrCreateAsync($"$cached-in-hybrid", async cancel =>
{
return await ValueTask.FromResult(new CacheData(DateTime.Now));
}, options: new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromSeconds(10d),//便于验证,设直10秒过期
LocalCacheExpiration = TimeSpan.FromSeconds(10d),
});
return Results.Content($"缓存的数据:{cachedDate.DateTime}");
}).WithDescription("多级缓存,避免分布式缓存的频繁序列化反序列化");
x.MapComponent<HelloWorld>("/razor/{key}",
context =>
{
return new { Key = context.Request.RouteValues["key"] };
});
});
//提供IQuickEndpoint支持:
routes.MapGroup("endpoints", x =>
{
//~/endpoints/hello/hello?key=world
x.MapMethods<HelloEndpoint>("hello/{hello}");
x.MapMethods<PostDataEndpoint>("hello/postdata");
//~/endpoints/hello/blazor-render-svc
x.MapMethods<BlazorRenderSvcEndpoint>("hello/blazor-render-svc");
//Feature测试
x.MapMethods<FeatureTestEndpoint>("hello/feature-test");
});
//测试特性管理
routes.MapGet(
"/new-feature",
() => Results.Content("new feature!"))
.WithMetadata(new FeatureGateAttribute("myfeature"));
// Identity API {"email" : "vipwan@co.ltd","password" : "*******"}
// ~/account/register
// ~/account/login
if (environment.IsDevelopment())
{
//当前preview4 BUG因此必须:ExcludeFromDescription()
routes.MapGroup("account").MapIdentityApi<IdentityUser>().ExcludeFromDescription();
}
else
{
routes.MapGroup("account").MapIdentityApi<IdentityUser>();
}
routes.MapGet("/hello-demo", (IOptions<DemoOptions> options) => options.Value.Name);
}
}
public class DemoOptions
{
public string Name { get; set; } = "Demo";
public bool Enable { get; set; } = true;
}
}