【发布时间】:2019-07-11 09:52:43
【问题描述】:
所以我四处寻找这个问题的答案,但我发现什么都没有接近解决它。
我正在尝试在我的 Web API 上设置 Post 方法,但无论我做什么,它都会给我一个内部服务器错误。
我尝试添加 [FromBody](这是一个简单的类型)。
HttpClient client {get;set;}
public APICall()
{
client = new HttpClient
{
BaseAddress = new Uri("http://localhost:1472/api/")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
}
public void PostTimeTaken(long timeTaken)
{
var response = client.PostAsJsonAsync("Logging", timeTaken).Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.ReasonPhrase);
}
}
然后我的控制器操作如下所示:
public void Post([FromBody] long timeTaken)
{
_api.DataBuilder.NumberOfAPICalls += 1;
_api.DataBuilder.ResponseTimes.Add(timeTaken);
}
我没有收到可以实际解释发生了什么的错误消息,只是“内部服务器错误”
--------已解决--------
以防万一有人偶然发现这个寻找相同的答案,问题是我以不正确的格式将数据发送到服务器,它需要首先被 ProtoBuf 序列化,代码 sn-p 对任何可能有帮助的人:
public void PostToAPI(int ThingToSend)
{
using (var stream = new MemoryStream())
{
// serialize to stream
Serializer.Serialize(stream, ThingToSend);
stream.Seek(0, SeekOrigin.Begin);
// send data via HTTP
StreamContent streamContent = new StreamContent(stream);
streamContent.Headers.Add("Content-Type", "application/x-protobuf");
var response = client.PostAsync("Logging", streamContent);
Console.WriteLine(response.Result.IsSuccessStatusCode);
}
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-web-api2 protocol-buffers