"回到目錄" LindDotNetCore中間件 大叔認識中間件就是主要對 http請求進行攔截 ,然後添加具體個性化功能的邏輯,這種把請求切開,添加新邏輯的方式一般稱為面向方面的邏輯AOP! 1. 授權中間件 2. 請求鏈跟蹤中間件 3. 響應時間中間件 授權中間件 請求有效性的校驗 授權參數 客 ...
LindDotNetCore中間件
大叔認識中間件就是主要對http請求進行攔截,然後添加具體個性化功能的邏輯,這種把請求切開,添加新邏輯的方式一般稱為面向方面的邏輯AOP!
- 授權中間件
- 請求鏈跟蹤中間件
響應時間中間件
授權中間件
請求有效性的校驗
授權參數
/// <summary> /// 授權配置 /// </summary> public class AuthorizationConfig { /// <summary> /// 統一密鑰 /// </summary> public string EncryptKey { get; set; } /// <summary> /// 過期時間秒數 /// </summary> public int ExpiredSecond { get; set; } /// <summary> /// 被授權的app /// </summary> public string[] AppList { get; set; } }
客戶端請求參數
/// <summary> /// 從http請求發過來的授權實體 /// </summary> public class AuthorizationRequestInfo { public string ApplicationId { get; set; } public string Timestamp { get; set; } public string Sinature { get; set; } }
請求攔截器,處理請求有效性,對app,過期時間,加密方式進行校驗
string computeSinature = MD5($"{requestInfo.ApplicationId}-{requestInfo.Timestamp}-{_options.EncryptKey}"); double tmpTimestamp; if (computeSinature.Equals(requestInfo.Sinature) && double.TryParse(requestInfo.Timestamp, out tmpTimestamp)) { if (ValidateExpired(tmpTimestamp, _options.ExpiredSecond)) { await ReturnTimeOut(context); } else { await ValidateApp(context, requestInfo.ApplicationId); } } else { await ReturnNotAuthorized(context); }
為開發人員提供友好的擴展方法,用來註冊中間件
/// <summary>
/// 註冊授權服務-step1
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
/// <param name="configureOptions">A delegate to configure the <see cref="ResponseCompressionOptions"/>.</param>
/// <returns></returns>
public static IServiceCollection AddLindAuthrization(this IServiceCollection services, Action<AuthorizationConfig> configureOptions = null)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var options = new AuthorizationConfig();
configureOptions?.Invoke(options);
ObjectMapper.MapperTo(options, ConfigFileHelper.Get<AuthorizationConfig>());
services.AddSingleton(options);
return services;
}
/// <summary>
/// 使用授權中間件-step2
/// </summary>
/// <param name="builder"></param>
/// <param name="options"></param>
/// <returns></returns>
public static IApplicationBuilder UseLindAuthrization(this IApplicationBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
var options = builder.ApplicationServices.GetService<AuthorizationConfig>();
return builder.UseMiddleware<AuthorizationMiddleware>(options);
}
- 使用授權中間件Startup中註冊
// 註冊服務
services.AddLindAuthrization(options =>
{
options.EncryptKey = "abc123";
options.ExpiredSecond = 50;
options.AppList = new string[] { "1", "2", "3" };
});
// 註冊中間件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseLindAuthrization();
app.UseMvc();
}
請求鏈跟蹤中間件
記錄請求經過的整個過程,對於多api相互調用的場景比較有用
響應時間中間件
記錄大於指定時間的請求信息,方便做性能整體的提升
回到目錄