使用PutAsync转发HttpPut请求

时间:2018-07-26 16:10:21

标签: c# .net .net-core

请问如何在C#中转发HttpPut请求?

到目前为止,这是我想要的,但是我想将SendAsync更改为PutAsync,但是PutAsync确实接受HttpRequestMessage类型。我正在尝试保留原始请求中的信息。

   public async Task<HttpResponseMessage> MyFunc(HttpRequestMessage request)
    {
        var url = "http://test.com/stuffgoeshere"

        UriBuilder forwardUri = new UriBuilder(url);
        request.RequestUri = forwardUri.Uri;

        var handler = new HttpClientHandler();
        using (var httpClient = new HttpClient(handler))
        {

            using (var client = new HttpClient(handler))
            {
                    var response = await client.PutAsync(request, HttpCompletionOption.ResponseHeadersRead);

                    return response;
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

Http Method(Verb)已经存在于Method方法属性中的HttpResponseMessage中,您可以根据需要进行设置或更改:

request.Method = HttpMethod.Put;

这就是为什么您可以在请求中轻松使用SendAsync的原因:

public async Task<HttpResponseMessage> MyFunc(HttpRequestMessage request)
{
    var url = "http://test.com/stuffgoeshere";

    UriBuilder forwardUri = new UriBuilder(url);
    request.RequestUri = forwardUri.Uri;
    request.Method = HttpMethod.Put;

    using (var client = new HttpClient())
    {
        var response = await client.SendAsync(request);
        return response;
    }
}

或者,如果HttpRequestMessage中的Method已设置,则只需执行SendAsync即可。