c# - .NET HttpClient : How to set the request method dynamically?

标签 c# .net 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;
    }

目前看来您必须使用:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";

最佳答案

HttpRequestMessage 包含采用 HttpMethod 实例的构造函数,但是没有现成的构造函数可以将 HTTP 方法字符串转换为 HttpMethod,因此您不能避免这种转换(以一种或另一种形式)。

但是你不应该在不同的 switch case 下有重复的代码,所以实现应该是这样的:

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

关于c# - .NET HttpClient : How to set the request method dynamically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41065932/

相关文章:

c# - P/调用 C# 到 C++

c# - 将多个相似的 XML 节点附加到 XML 文档

c# - 仁慈SSH.NET : How to delete nonempty directory?

.net - 是否可以将 Reflection.Emit 用于操作码 stelem.any 和 ldelem.any?

c++ - 在 MySQL 中运行 HTTP 服务器以接收来自客户端的数据

php - 如何在 Guzzle 中设置引用 header

c# - 如何强制 WeakReference 死亡?

c# - Visual Studio 引用不再存在的命名空间

c# - 将 PNG 图像转换为 ZPL 代码

http - 使用 NodeJS,解析不一定结束的文件上传的最佳方法是什么?