在c#中检索Http客户端的POST请求体

本文关键字:POST 请求 客户端 Http 检索 | 更新日期: 2023-09-27 17:52:54

如何在c#中检索Http客户端的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;
    }

在c#中检索Http客户端的POST请求体

尝试使用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;           
    }