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):

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

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
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With