.NET HttpClient:如何动态设置请求方法?

8
如何使用HttpClient并动态设置方法而无需像这样做任何事情:
    public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)
    {
        HttpResponseMessage response;

        using (var client = new HttpClient())
        {
            switch (method.ToUpper())
            {
                case "POST":
                    response = await client.PostAsync(url, content);
                    break;
                case "GET":
                    response = await client.GetAsync(url);
                    break;
                default:
                    response = null;
                    // Unsupported method exception etc.
                    break;
            }
        }

        return response;
    }

目前看来,您需要使用:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";

1
您可以使用httprequestmessage设置方法、URL和内容。然后使用httpclient的send方法。 - Nkosi
请注意,不应该在每个请求中使用 new HttpClient(),否则在大规模情况下会耗尽套接字池。请使用单个静态实例。 - Matt Johnson-Pint
4个回答

9

HttpRequestMessage包含一个构造函数,该构造函数采用HttpMethod实例作为参数,但没有现成的构造函数将HTTP方法字符串转换为HttpMethod,所以您无法避免使用switch(以一种或另一种形式)。

但是,您不应该在不同的switch情况下复制相同的代码,因此实现应该类似于:

private HttpMethod CreateHttpMethod(string method)
{
    switch (method.ToUpper())
    {
        case "POST":
            return HttpMethod.Post;
        case "GET":
            return HttpMethod.Get;
        default:
            throw new NotImplementedException();
    }
}

public async Task<HttpResponseMessage> DoRequest(string url, HttpContent content, string method)
{
    var request = new HttpRequestMessage(CreateHttpMethod(method), url)
    {
        Content = content
    };

    return await client.SendAsync(request);
}

如果你不喜欢使用 switch ,可以使用以字符串为键的字典方法来避免它,但这种解决方案并不会更简单或更快。


1
你也可以将 HttpMethod httpMethod 作为参数传入,然后执行 new HttpRequestMessage(httpMethod, url) - Ed Harrod

8

但是目前没有可用的构造函数将 HTTP 方法字符串转换为 HttpMethod。

现在不再是这样了...1

public HttpMethod(string method);

可以像这样使用:

var httpMethod = new HttpMethod(method.ToUpper());

这是可运行的代码。
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace MyNamespace.HttpClient
{
public static class HttpClient
{
    private static readonly System.Net.Http.HttpClient NetHttpClient = new System.Net.Http.HttpClient();
    static HttpClient()
    {}

    public static async System.Threading.Tasks.Task<string> ExecuteMethod(string targetAbsoluteUrl, string methodName, List<KeyValuePair<string, string>> headers = null, string content = null, string contentType = null)
    {
        var httpMethod = new HttpMethod(methodName.ToUpper());

        var requestMessage = new HttpRequestMessage(httpMethod, targetAbsoluteUrl);

        if (!string.IsNullOrWhiteSpace(content) || !string.IsNullOrWhiteSpace(contentType))
        {
            var contentBytes = Encoding.UTF8.GetBytes(content);
            requestMessage.Content = new ByteArrayContent(contentBytes);

            headers = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Content-type", contentType)
            };
        }

        headers?.ForEach(kvp => { requestMessage.Headers.Add(kvp.Key, kvp.Value); });

        var response = await NetHttpClient.SendAsync(requestMessage);

        return await response.Content.ReadAsStringAsync();

    }
}
}

MSDN链接现在无法访问。请更改为https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpmethod.-ctor?view=netframework-4.7.2#System_Net_Http_HttpMethod__ctor_System_String_。 - sky91
@ Tsahi Ahser - 感谢您编辑资源链接! - Mark D.

1

.Net Core

var hc = _hcAccessor.HttpContext;

var hm = new HttpMethod(hc.Request.Method.ToUpper());
var hrm = new HttpRequestMessage(hm, 'url');

0

.NET Core 后续版本:

HttpClient client = new HttpClient();

// Add headers etc...

// Post
response = await client.PostAsync(uri, content);

// Get
response = await client.GetAsync(uri);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接