[英].NET HttpClient: How to set the request method dynamically?
How can one use HttpClient and set the method dynamically without having to do something like:如何使用 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;
}
At the moment it looks like you would have to use:目前看来您必须使用:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
but there is no ready constructor that converts HTTP method string to HttpMethod
但是没有现成的构造函数将HTTP方法字符串转换为HttpMethod
Well that's not true any longer... 1 那不再是真的...... 1
public HttpMethod(string method);
Can be used like this: 可以像这样使用:
var httpMethod = new HttpMethod(method.ToUpper());
Here is working code. 这是工作代码。
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();
}
}
}
HttpRequestMessage
contains constructor taking instance of HttpMethod
but there is no ready constructor that converts HTTP method string to HttpMethod
, so you can't avoid that switch (in one form or another). HttpRequestMessage
包含构造函数获取HttpMethod
实例,但是没有现成的构造函数将HTTP方法字符串转换为HttpMethod
,因此您无法避免该开关(以某种形式)。
However you should not have duplicated code under different switch cases, so implementation would be something like this: 但是,在不同的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);
}
If you don't like that switch
you could avoid it using Dictionary with method string as a key, however such solution will not be simpler or faster. 如果你不喜欢那个
switch
你可以避免使用带有方法字符串作为键的字典,但是这样的解决方案不会更简单或更快。
.Net Core .Net核心
var hc = _hcAccessor.HttpContext;
var hm = new HttpMethod(hc.Request.Method.ToUpper());
var hrm = new HttpRequestMessage(hm, 'url');
.NET Core later versions: .NET 核心更新版本:
HttpClient client = new HttpClient();
// Add headers etc...
// Post
response = await client.PostAsync(uri, content);
// Get
response = await client.GetAsync(uri);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.