gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:24:28 28 4
gpt4 key购买 nike

我有一个自托管的 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com