Post an empty body to REST API via HttpClient

限于喜欢 提交于 2019-12-31 17:35:20

问题


The API I'm trying to call requires that I do a POST but with an empty body. I'm new to using the WCF Web API HttpClient and I can't seem to find out the write code that would do a post with an empty body. I find references to some HttpContent.CreateEmpty() method, but I don't think that is for the Web API HttpClient code since I can't seem to find that method.


回答1:


Use StringContent or ObjectContent which derive from HttpContent or you can use null as HttpContent (see this comment).




回答2:


Did this before, just keep it simple:

Task<HttpResponseMessage> task = client.PostAsync(url, null);



回答3:


Have found that:

Task<HttpResponseMessage> task = client.PostAsync(url, null);

Adds null to the request body, which failed on WSO2. Replaced with:

Task<HttpResponseMessage> task = client.PostAsync(url, new {});

And worked.




回答4:


I think it does that automagically if your web method has no parameters or they all fit into URL template.

For example this declaration sends empty body:

  [OperationContract]
  [WebGet(UriTemplate = "mykewlservice/{emailAddress}",
     RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
     BodyStyle = WebMessageBodyStyle.Wrapped)]
  void GetStatus(string emailAddress, out long statusMask);


来源:https://stackoverflow.com/questions/7907648/post-an-empty-body-to-rest-api-via-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!