簡體   English   中英

在C#中檢索Http客戶端的POST請求正文

[英]Retrieve POST Request Body of Http client in C#

有什么方法可以在C#中檢索Http Client的POST請求正文? 我只想檢查我的UT是否將我的擴展方法正確地添加到請求中。 此功能對此沒有任何公正性。

public static async Task<string> AddPostRequestBody<T>(this HttpClient httpclient, string RequestUrl, T classobject)
    {
        string json_body = Newtonsoft.Json.JsonConvert.SerializeObject(classobject);
        HttpRequestMessage RequestMessage = new HttpRequestMessage(HttpMethod.Post, RequestUrl);
        HttpResponseMessage response = await httpclient.PostAsync(RequestUrl, new StringContent(json_body));
        response = httpclient.SendAsync(RequestMessage).Result;
        string outputresult = await response.RequestMessage.Content.ReadAsStringAsync();
        return outputresult;
    }

請幫忙 !

嘗試使用DelegatingHandler(我在實現HMAC時用來對內容進行哈希處理並添加必要的授權標頭),這將使您能夠訪問內容。

CustomDelegatingHandler customDelegatingHandler = new CustomDelegatingHandler();
HttpClient client = HttpClientFactory.Create(customDelegatingHandler);

public class CustomDelegatingHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            byte[] content = await request.Content.ReadAsByteArrayAsync();
            // Do what you need with the content here
        }

        response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}

好的,所以我可以使用它而不是創建響應,而是直接附加到請求消息並從中檢索。 很簡單,但最初在發布的問題中,我通過在響應中添加json字符串使其變得復雜。

public static string AddPostRequestBody<T>(this HttpClient httpclient, string requestUrl, T classObject)
    {
        string jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(classObject);
        HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl);
        requestMessage.Content = new StringContent(jsonBody);
        string requestBody = requestMessage.Content.ReadAsStringAsync().Result;
        return requestBody;           
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM