Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# HttpClient POST到WCF返回400个错误请求_C#_Json_Wcf - Fatal编程技术网

C# HttpClient POST到WCF返回400个错误请求

C# HttpClient POST到WCF返回400个错误请求,c#,json,wcf,C#,Json,Wcf,我有一个自托管的WCF服务,它公开了一个带有以下签名的Web POST方法: [ServiceContract] public interface IPublisherService { [OperationContract] [WebInvoke(UriTemplate = "Send", Method = "POST")] void SendMessage(string message); } 如果我使用具有以下结构()的Fiddler发送请求: WCF返回200

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

[ServiceContract]
public interface IPublisherService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "Send", Method = "POST")]
    void SendMessage(string message);
}
如果我使用具有以下结构()的Fiddler发送请求:

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

但是,当我试图从C#Console应用程序中使用HttpClient时,我总是无缘无故地返回400个错误请求。 请求如下:

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


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

从数据库检索数据时,当HttpClient请求超过默认的30秒超时时,出现错误400错误请求。sql中增加超时有帮助。

您是否尝试添加
accept:application/json
标题?将
application/json
更改为
application/json
是,这没关系,问题是字符串本身,我必须使用JsonFormatter才能让WCF接受我的请求。我创造了一个答案,我不知道是否能对别人有所帮助
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();
}