Reputation: 6973
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
}
Upvotes: 4
Views: 12830
Reputation: 598
I had error 400 Bad Request when HttpClient request exceed default 30 seconds timeout while retrieving data from database. Increased timeout in sql helps.
Upvotes: 0
Reputation: 6973
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();
}
Upvotes: 2