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