.NET HttpClient:如何动态设置请求方法?
.NET HttpClient: How to set the request method dynamically?
如何使用 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 情况下你不应该有重复的代码,所以实现应该是这样的:
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
您可以避免使用以方法字符串为键的字典,但是这样的解决方案不会更简单或更快。
but there is no ready constructor that converts HTTP method string to 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();
}
}
}
.网络核心
var hc = _hcAccessor.HttpContext;
var hm = new HttpMethod(hc.Request.Method.ToUpper());
var hrm = new HttpRequestMessage(hm, 'url');
.NET Core 更高版本:
HttpClient client = new HttpClient();
// Add headers etc...
// Post
response = await client.PostAsync(uri, content);
// Get
response = await client.GetAsync(uri);
如何使用 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 情况下你不应该有重复的代码,所以实现应该是这样的:
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
您可以避免使用以方法字符串为键的字典,但是这样的解决方案不会更简单或更快。
but there is no ready constructor that converts HTTP method string to 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();
}
}
}
.网络核心
var hc = _hcAccessor.HttpContext;
var hm = new HttpMethod(hc.Request.Method.ToUpper());
var hrm = new HttpRequestMessage(hm, 'url');
.NET Core 更高版本:
HttpClient client = new HttpClient();
// Add headers etc...
// Post
response = await client.PostAsync(uri, content);
// Get
response = await client.GetAsync(uri);