ste*_*ood 3 .net c# http webrequest dotnet-httpclient
如何使用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;
}
Run Code Online (Sandbox Code Playgroud)
目前它看起来你将不得不使用:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
Run Code Online (Sandbox Code Playgroud)
HttpRequestMessage
包含构造函数获取实例HttpMethod
但没有现成的构造函数将HTTP方法字符串转换为HttpMethod
,因此您无法避免该开关(以一种或另一种形式).
但是,在不同的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);
}
Run Code Online (Sandbox Code Playgroud)
如果你不喜欢它,switch
你可以使用带有方法字符串作为键的字典来避免它,但是这样的解决方案不会更简单或更快.
小智 6
但是没有现成的构造函数可以将HTTP方法字符串转换为HttpMethod
好吧,这不再是真的... 1
public HttpMethod(string method);
Run Code Online (Sandbox Code Playgroud)
可以这样使用:
var httpMethod = new HttpMethod(method.ToUpper());
Run Code Online (Sandbox Code Playgroud)
这是工作代码。
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)