![](/img/trans.png)
[英].NET WebApi HttpClient not sending Windows Authentication credentials to same domain
[英]Sending json with .NET HttpClient to a WebAPI server
我正在嘗試使用HttpClient
通過POST將json發送到我的Web服務。
發送方法真的很簡單:
HttpClient _httpClient = new HttpClient();
public async Task<HttpStatusCode> SendAsync(Data data)
{
string jsonData = JsonConvert.SerializeObject(data);
var content = new StringContent(
jsonData,
Encoding.UTF8,
"application/json");
HttpResponseMessage response = await _httpClient.PostAsync(_url, content);
return response.StatusCode;
}
在服務器端,我具有使用以下方法的WebAPI控制器:
[HttpPost]
[ActionName("postdata")]
public async Task<HttpResponseMessage> PostData([FromBody] string jsonParam)
{
/// here the jsonParam is null when receiving from HttpClient.
// jsonParam gets deserialized, etc
}
此方法中的jsonParam為null
。 jsonData
很好,如果我將其復制並粘貼到請求發件人(我使用郵遞員)中,一切都將成功。
這是關於如何構造內容並使用HttpClient
但我無法弄清楚出了什么問題。
誰能看到這個問題?
由於您嘗試發布json,因此您可以添加對System.Net.Http.Formatting的引用並直接發布“數據”,而無需對其進行序列化和創建StringContent。
public async Task<HttpStatusCode> SendAsync(Data data)
{
HttpResponseMessage response = await _httpClient.PostAsJsonAsync(_url, content);
return response.StatusCode;
}
在接收方,您可以直接接收“數據”類型。
[HttpPost]
[ActionName("postdata")]
public async Task<HttpResponseMessage> PostData(Data jsonParam)
{
}
有關這些HttpClientExtensions方法的更多信息,可以在這里找到-http: //msdn.microsoft.com/zh-cn/library/hh944521( v=vs.118) .aspx
發布單個簡單類型時,您需要在發布正文上使用特殊語法:
=postBodyText
而且,您必須將Content-Type
更改為application/x-www-form-urlencoded
。
參考: http : //www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-1#sending_simple_types
對於初學者,這應該起作用:
public async Task<HttpStatusCode> SendAsync(Data data)
{
string jsonData = string.Format("={0}", JsonConvert.SerializeObject(data));
var content = new StringContent(
jsonData,
Encoding.UTF8,
"application/x-www-form-urlencoded");
HttpResponseMessage response = await _httpClient.PostAsync(_url, content);
return response.StatusCode;
}
或者,您可能會在控制器中收到復雜的類型而不是字符串。
[HttpPost]
[ActionName("postdata")]
public async Task<HttpResponseMessage> PostData(Data data)
{
// do stuff with data: in this case your original client code should work
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.