我试图调用的API需要一个具有空主体的POST。我正在使用WCF Web API HttpClient,我找不到正确的代码,将发布一个空的主体。我找到了一些HttpContent.CreateEmpty()方法的引用,但我不认为它是为Web API HttpClient代码,因为我似乎找不到该方法。
当前回答
要解决这个问题,请使用下面的例子:
using (var client = new HttpClient())
{
var stringContent = new StringContent(string.Empty);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = client.PostAsync(url, stringContent).Result;
var result = response.Content.ReadAsAsync<model>().Result;
}
其他回答
发现:
Task<HttpResponseMessage> task = client.PostAsync(url, null);
向请求体中添加null,该请求体在WSO2上失败。替换为:
Task<HttpResponseMessage> task = client.PostAsync(url, new {});
和工作。
之前做过,保持简单:
Task<HttpResponseMessage> task = client.PostAsync(url, null);
要解决这个问题,请使用下面的例子:
using (var client = new HttpClient())
{
var stringContent = new StringContent(string.Empty);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = client.PostAsync(url, stringContent).Result;
var result = response.Content.ReadAsAsync<model>().Result;
}
使用StringContent或ObjectContent派生自HttpContent,或者你可以使用null作为HttpContent:
var response = await client.PostAsync(requestUri, null);
我认为如果你的web方法没有参数,或者它们都适合URL模板,它就会自动做到这一点。
例如,这个声明发送空的主体:
[OperationContract]
[WebGet(UriTemplate = "mykewlservice/{emailAddress}",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
void GetStatus(string emailAddress, out long statusMask);
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 无法在Windows 8的IIS中提供WCF服务
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?