HttpClient POST to WCF returns 400 Bad Request

11,303

I don't know if it make sense but the answer is my string content is not properly formatted. I have changed the request using Newtonsoft.Json and now it works:

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();
}
Share:
11,303
Raffaeu
Author by

Raffaeu

I am Raffaeu (Raffaele Garofalo), Software Architect and passionate about Software Development and Architecture in general.

Updated on June 07, 2022

Comments

  • Raffaeu
    Raffaeu almost 2 years

    I have a WCF Service self-hosted which exposes a Web POST method with the following signature:

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

    If I send a request using Fiddler with the following structure (http://localhost:8080/Publisher/Send):

    enter image description here

    WCF returns 200 OK with the response correctly deserialized into JSON:

    enter image description here

    But when I try to use HttpClient from a C# Console Application, I always get back a 400 Bad Request without any reason. This is the 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();
    }
    

    And the response is always 400, doesn't matter if I use client.PostAsync or 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
    }