使用 System.Net.Http.HttpClient 时有没有办法参数化 HTTP 方法?
Is there a way to parameterize the HTTP method when using System.Net.Http.HttpClient?
我在 .Net 核心 3.1 中使用 HttpClient
。无论使用何种 HTTP 方法,我的大部分请求都遵循类似的模式:
- 建设URL
- 构建(可选)JSON 有效负载
- 发送请求
- 等待回复
- 检查状态码
- 解析(可选)JSON响应
所以我构建了一个包装器函数来完成所有这些事情,并将 HTTP 方法作为参数。但是,当涉及到"send request"这一步时,我需要使用switch语句来调用HttpClient上相应的方法来调用。
我确信在表面之下,getAsync() PostAsync() 等正在调用相同的底层函数并将 Http 方法作为参数传递。但我看不出有什么方法可以从外面这样称呼它。这似乎是一个奇怪的遗漏,因为根据我的经验,大多数 HTTP 库都是这样工作的。
希望对您有所帮助。
// For JsonConvert use Newtonsoft.Json
string url = "YourURL";
string body = JsonConvert.SerializeObject(BodyModel);
string headerParameter = "ASD123456789";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Content-Type of request, it can be application/xml to other
client.DefaultRequestHeaders.Add("Device", headerParameter ); // first is name, second one is value
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) // there you can have Get, Post, Put, Delete and etc. And every request needs to be configured by its settings
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
string responseString = await response.Content.ReadAsStringAsync();
ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
}
我在 .Net 核心 3.1 中使用 HttpClient
。无论使用何种 HTTP 方法,我的大部分请求都遵循类似的模式:
- 建设URL
- 构建(可选)JSON 有效负载
- 发送请求
- 等待回复
- 检查状态码
- 解析(可选)JSON响应
所以我构建了一个包装器函数来完成所有这些事情,并将 HTTP 方法作为参数。但是,当涉及到"send request"这一步时,我需要使用switch语句来调用HttpClient上相应的方法来调用。
我确信在表面之下,getAsync() PostAsync() 等正在调用相同的底层函数并将 Http 方法作为参数传递。但我看不出有什么方法可以从外面这样称呼它。这似乎是一个奇怪的遗漏,因为根据我的经验,大多数 HTTP 库都是这样工作的。
希望对您有所帮助。
// For JsonConvert use Newtonsoft.Json
string url = "YourURL";
string body = JsonConvert.SerializeObject(BodyModel);
string headerParameter = "ASD123456789";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Content-Type of request, it can be application/xml to other
client.DefaultRequestHeaders.Add("Device", headerParameter ); // first is name, second one is value
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) // there you can have Get, Post, Put, Delete and etc. And every request needs to be configured by its settings
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(request);
if ((int)response.StatusCode == 200)
{
string responseString = await response.Content.ReadAsStringAsync();
ResponseModel responseModel = JsonConvert.DeserializeObject<ResponseModel>(responseString);
}