簡體   English   中英

HttpClient POST 到 WCF 返回 400 Bad Request

[英]HttpClient POST to WCF returns 400 Bad Request

我有一個 WCF 服務自托管,它公開了一個具有以下簽名的 Web POST 方法:

[ServiceContract]
public interface IPublisherService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "Send", Method = "POST")]
    void SendMessage(string message);
}

如果我使用具有以下結構的 Fiddler 發送請求( http://localhost:8080/Publisher/Send ):

在此處輸入圖片說明

WCF 返回 200 OK 並將響應正確反序列化為 JSON:

在此處輸入圖片說明

但是當我嘗試從 C# 控制台應用程序使用HttpClient 時,我總是無緣無故地返回 400 Bad Request。 這是請求:

using (HttpClient client = new HttpClient())
{
    var content = new StringContent(this.view.Message);
    content.Headers.ContentType = new MediaTypeHeaderValue("Application/Json");
    var response = client.PostAsync(
        new Uri("http://localhost:8080/Publisher/Send"), 
        content);
    var result = response.Result;
    this.view.Message = result.ToString();
}

響應始終為 400,無論我使用client.PostAsync還是clint.SendAsync都沒有關系。

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Tue, 29 Dec 2015 12:41:55 GMT
  Server: Microsoft-HTTPAPI/2.0
  Content-Length: 1647
  Content-Type: text/html
}

我不知道這是否有意義,但答案是我的字符串內容格式不正確 我已經使用 Newtonsoft.Json 更改了請求,現在它可以工作了:

using (HttpClient client = new HttpClient())
{                
    var request = new StringContent(
        JsonConvert.SerializeObject(this.view.Message), 
        Encoding.UTF8, 
        "application/json");
    var response = client.PostAsync(
        new Uri("http://localhost:8080/Publisher/Send"), 
        request);
    var result = response.Result;
    view.Message = result.ToString();
}

當從數據庫中檢索數據時 HttpClient 請求超過默認的 30 秒超時時,我遇到了錯誤 400 Bad Request。 增加 sql 中的超時有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM