繁体   English   中英

.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";

但是没有现成的构造函数将HTTP方法字符串转换为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();

    }
}
}

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你可以避免使用带有方法字符串作为键的字典,但是这样的解决方案不会更简单或更快。

.Net核心

var hc = _hcAccessor.HttpContext;

var hm = new HttpMethod(hc.Request.Method.ToUpper());
var hrm = new HttpRequestMessage(hm, 'url');

.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM