Sim*_*max 8 c# asp.net-web-api
我需要HTTP POST一个复杂的类型到Web服务(我无法控制).我相信Web服务是使用旧版本的ASP.NET MVC构建的.它模型绑定格式为的有效负载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;
Run Code Online (Sandbox Code Playgroud)
但我不想这样做,我只想发送复杂的类型,如果可以的话.
var content = new ComplexType("some-username", "some-password", "some-product");
var response = new HttpClient().PostAsync(url, content).Result;
Run Code Online (Sandbox Code Playgroud)
我相信曾经有一个HttpRequestMessage<T>但是已经被抛弃了
HttpClient.PostAsJsonAsync<T>(T value) sends “application/json”
HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”
但是我不想发送Json或者XML我想发送form-url-ecncoded而没有将复杂类型转换为键/值对集合的麻烦.
基本上我也想知道 Jaans提出的这个问题的答案 (他是对第二个答案的第二个评论).
任何人都可以提出建议.
既然你几乎已经找到了一个可行的解决方案,我会说就用它吧。在扩展方法中组织您的代码,以便您可以使用它进行发布,例如:
public static async Task<HttpResponseMessage> PostAsFormUrlEncodedAsync<T>(
this HttpClient httpClient, T value)
{
// Implementation
}
Run Code Online (Sandbox Code Playgroud)
您的实现只需将对象序列化为表单编码值,您应该能够通过反射轻松完成此操作。
然后,您可以像调用 JSON 或 XML 一样调用该代码。
| 归档时间: |
|
| 查看次数: |
3891 次 |
| 最近记录: |