c# - 使用 ASP.Net HttpClient 将复杂类型格式化为 form-url-encoded

标签 c# asp.net-web-api

我需要HTTP POST Web 服务的复杂类型(我无法控制)。我相信 Web 服务是使用旧版本的 ASP.NET MVC 构建的。它模型绑定(bind)格式为 form-url-encoded 的有效负载.

如果我向它发射以下命令,它会完美运行。如您所见,我手动创建了一个键/值对集合。

    var values = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("Username", "some-username"),
        new KeyValuePair<string, string>("Password", "some-password"),
        new KeyValuePair<string, string>("Product", "some-product")
    };

    var content = new FormUrlEncodedContent(values);

    var response = new HttpClient().PostAsync(url, content).Result;

但我不想必须这样做,我只想尽可能发送复杂类型。

var content = new ComplexType("some-username", "some-password", "some-product");

var response = new HttpClient().PostAsync(url, content).Result;

我相信曾经有一个 HttpRequestMessage<T>但这已被放弃以支持

HttpClient.PostAsJsonAsync<T>(T value) sends “application/json” HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”

但我不想发送JsonXML我要发form-url-ecncoded无需将复杂类型转换为键/值对集合的麻烦。

基本上我也想知道 this question 的答案Jaans 提出的(他是对第二个答案的第二条评论)。

谁能给点建议。

最佳答案

Flurl [披露:我是作者] 提供了一种似乎正是您正在寻找的方法:

using Flurl.Http;

var resp = await url.PostUrlEncodedAsync(new {
    Username = "some-username",
    Password = "some-password",
    Product = "some-product",
});

Flurl 小巧便携,并在底层使用 HttpClient。它可以通过 NuGet 获得:

PM> Install-Package Flurl.Http

关于c# - 使用 ASP.Net HttpClient 将复杂类型格式化为 form-url-encoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217744/

相关文章:

c# - DocumentDB 客户端生命周期

asp.net-mvc - 如何绕过在 ASP.NET Web API 中发现多个操作的异常

javascript - 无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“TenantManagementWebApi.Entities.Tenant”

.net - 如何在 web api 中处理重复的帖子请求

excel - Azure Active Directory - 为什么没有注册的浏览器可以进行身份​​验证,但不是第一方应用程序?

c# - Azure Blob 的 sqlCacheDependency

c# - 如何在主应用程序线程中自动捕获 Task 对象的操作引发的异常?

c# - 我的类不能用作泛型类型中的类型参数 'TEventArgs' 或 .Net 4 中的方法 'System.EventHandler<TEventArgs>'

c# - SQLite 简单插入查询

asp.net-web-api - Asp.net Web Api 将 UTC 时间字符串反序列化为本地时间