【问题标题】:.NET HttpClient: How to set the request method dynamically?.NET HttpClient:如何动态设置请求方法?
【发布时间】:2024-01-07 14:39:01
【问题描述】:

如何使用 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";

【问题讨论】:

  • 可以httprequestmessage并设置方法、url和内容。然后使用httpclient的send方法
  • 请注意,您不应针对每个请求 new HttpClient(),否则您可能会大规模耗尽您的套接字池。使用单个静态实例。

标签: c# .net http webrequest dotnet-httpclient


【解决方案1】:

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

但是你不应该在不同的 switch case 下有重复的代码,所以实现应该是这样的:

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,您可以使用 Dictionary 和方法字符串作为键来避免它,但是这样的解决方案不会更简单或更快。

【讨论】:

  • 也可以将HttpMethod httpMethod作为参数传入,然后做new HttpRequestMessage(httpMethod, url)
【解决方案2】:

但没有现成的构造函数将 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();

    }
}
}

【讨论】:

【解决方案3】:

.Net 核心

var hc = _hcAccessor.HttpContext;

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

【讨论】: