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

时间:2016-06-29 08:07:37

标签: c# asp.net-mvc http-post httpclient http-request

以何种方式在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;
    }

请帮忙!

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

好的,所以我得到了它而不是创建响应,我直接附加到请求消息并从中检索。简单但最初在发布的问题中,我通过将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;           
    }