首页 文章

HttpClient POST到WCF返回400 Bad Request

提问于
浏览
1

我有一个自托管的WCF服务,它使用以下签名公开Web POST方法:

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

如果我使用具有以下结构的Fiddler发送请求(http://localhost:8080/Publisher/Send):

enter image description here

WCF返回200 OK,响应正确反序列化为JSON:

enter image description here

但是当我尝试从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
}

1 回答

  • 1

    我不知道它是否有意义,但答案是我的字符串内容格式不正确 . 我已经使用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();
    }
    

相关问题