欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.NET Framework攔截HTTP請求的實(shí)現(xiàn)

 更新時(shí)間:2024年03月06日 09:24:18   作者:菜鳥厚非  
本文主要介紹了.NET Framework攔截HTTP請求的實(shí)現(xiàn),主要用于記錄 HTTP 信息,調(diào)試程序、分析程序性能等方面,具有一定的參考價(jià)值,感興趣的可以了解一下

一、簡介

今天講一下 .NET Framework 程序中攔截 HTTP 請求,這主要用于記錄 HTTP 信息,調(diào)試程序、分析程序性能等方面。這里貼出實(shí)現(xiàn)的核心代碼,具體需要結(jié)合自己的業(yè)務(wù)。

二、實(shí)現(xiàn)代碼

創(chuàng)建一個(gè)普通的 HTTPInterceptortHandler 類 ,繼承 DelegatingHandler 類,并重寫 SendAsync 方法

public class HTTPInterceptortHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // 根據(jù)需求調(diào)試,獲取更多數(shù)據(jù)
        string requestIP = HttpContext.Current?.Request?.UserHostAddress;
        string requestContent = request.Content?.ReadAsStringAsync()?.Result;
        string requestUri = request.RequestUri.AbsoluteUri;

        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(
            (task) =>
            {
                string responseContent = task.Result.Content.ReadAsStringAsync().Result;
                string responseCode = task.Result.StatusCode.ToString();

                // 記錄日志、加工一下結(jié)果等都可以在這里處理

                return task.Result;
            }
        );
    }
}

在 Global.asax 的 Application_Start 方法中注冊寫好的 HTTPInterceptortHandler 類

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // 在 Application_Start 方法添加這一行
        GlobalConfiguration.Configuration.MessageHandlers.Add(new HTTPInterceptortHandler()); 
    }
}

到此這篇關(guān)于.NET Framework攔截HTTP請求的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān).NET Framework攔截HTTP內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論