Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient POST to WCF returns 400 Bad Request

Tags:

json

c#

wcf

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
}
like image 364
Raffaeu Avatar asked Nov 01 '25 23:11

Raffaeu


1 Answers

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();
}
like image 95
Raffaeu Avatar answered Nov 03 '25 14:11

Raffaeu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!