c# - 如果我在 web api 中创建一个委托处理程序来执行一些预处理逻辑。它会妨碍性能吗?
问题描述
我创建了一个委托处理程序来处理我的预处理逻辑。该逻辑只是检查我们在请求中具有的任何特殊字符,然后对其进行编码并在生命周期中继续前进。下面是代码:
public class EncodingRequest : DelegatingHandler
{
protected override async Task<System.Net.Http.HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//deserialize the request that is in json format
dynamic dynamicJson = JsonConvert.DeserializeObject(request.Content.ReadAsStringAsync().Result);
//using regex to match the pattern for the Json request object and directly replacing and encoding the desired value
//SUGGESTION: Used JSon JProperties to modified the request by encoding it. This was taking more loop as we need to go through every child element of Json
//If the JSON have child hierarchy(a child having its own child and so on) then we have to loop to each child to encode the request. So, more convenient way was
//to use regex Replace method that matches the pattern and replace it with the new value.
string regexPattern = "(?<=: \")[^\",\r\n]*";
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(regexPattern);
//using REGEX's replace function to find the matching pattern and then replace the value with the encoded value
dynamicJson = rgx.Replace(dynamicJson.ToString(), new MatchEvaluator((m) => { return Encoder.HtmlEncode(m.ToString()); }));
//chanding the request content with the modified request with header type as "application/json"
request.Content = new StringContent(dynamicJson,
System.Text.Encoding.UTF8,
"application/json");//CONTENT-TYPE header
Core.Logging.LogManager.LogVerbose(request.Content.ReadAsStringAsync().Result);
//original call
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Core.Logging.LogManager.LogVerbose(response.ToString());
return response;
}
}
所以,这是按预期工作的。但是,这会妨碍我的 web api 的性能吗?如果是,它将如何阻碍以及我应该使用什么其他技术。如果是 WCF,那么我会使用运行时架构(IServiceBehavior、IOOperationBehavior)。如果它妨碍性能,我将如何使用 Delegating Handler。
解决方案
推荐阅读
- php - WooCommerce:从产品页面上的产品属性中获取元字段
- linux - 在 unbuntu 和 nginx 上托管多个 ASP NET Core 站点作为反向代理
- pandas - 熊猫数据框 [] 问题
- c++ - 如何使用 BCrypt 进行 RSA(非对称加密)
- ruby - 如何使用 Ruby 将另一个字段的值添加到 HTTParty 字段
- android - 如何在 Android 中制作淡入淡出的状态栏?
- swift - 将 BLE 当前时间转换为日期
- javascript - 使用 MediaRecorder 录制时如何获取录制时间
- python - 如何使用 Tkinter 创建网格?
- python - 从热图数据生成边界框