c# - HttpClient POST 到 WCF 返回 400 错误请求

标签 c# json wcf

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

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

如果我使用具有以下结构 ( http://localhost:8080/Publisher/Send ) 的 Fiddler 发送请求:

enter image description here

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

enter image description here

但是当我尝试从 C# 控制台应用程序使用 HttpClient 时,我总是无缘无故地返回 400 Bad 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();
}

响应始终为 400,无论我使用 client.PostAsync 还是 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
}

最佳答案

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

关于c# - HttpClient POST 到 WCF 返回 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34511322/

相关文章:

php - 带有 php : Saving utf-8 string to MySQL 的安卓系统

c# - 序列化同一个类中的多个 DateTime 属性,每个属性使用不同的格式

c# - 处理错误 "WebDev.WebServer.Exe has stopped working"

c# - OpenXml:工作表子元素的顺序更改导致文件损坏

javascript - 如何将 JSON 数组属性值从数组转换为键

wcf - 从 Web 应用程序调用时自托管 WCF 服务中的线程标识

c# - WCF 模拟的目的

HTTPS 上的 WCF 生成 "The provided URI scheme ' https' 无效;预期为 'http'。”

c# - INeedSomething 的更好名字...?

c# - 如何从 Utf8JsonReader 获取属性路径?