gpt4 book ai didi

c# - .NET HttpClient : How to set the request method dynamically?

转载 作者:可可西里 更新时间:2023-11-01 15:30:40 30 4
gpt4 key购买 nike

如何使用 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 包含采用 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,但是这样的解决方案不会更简单或更快。

关于c# - .NET HttpClient : How to set the request method dynamically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41065932/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com