首页 > 解决方案 > 如果我在 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。

标签: c#restasp.net-web-apiasp.net-web-api2

解决方案


推荐阅读