HttpClient.PostAsJsonAsync内容为空

HttpClient.PostAsJsonAsync content empty

我正在尝试使用 ASP.net MVC 将复杂数据类型从一个进程发送到另一个进程。由于某种原因,接收端总是收到空白(zero/default)数据。

我的发送方:

static void SendResult(ReportResultModel result)
{
    //result contains valid data at this point

    string portalRootPath = ConfigurationManager.AppSettings["webHost"];
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(portalRootPath);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage resp = client.PostAsJsonAsync("Reports/MetricEngineReport/MetricResultUpdate", result).Result;
    if (!resp.IsSuccessStatusCode) {
    //I've confirmed this isn't happening by putting a breakpoint in here.
    }
}

我的接收端,在不同的 class,运行 在我本地机器上的不同进程中:

public class MetricEngineReportController : Controller
{
    ...
    [HttpPost]
    public void MetricResultUpdate(ReportResultModel result)
    {
        //this does get called, but
        //all the guids in result are zero here :(
    }
    ...
}

我的模型有点复杂:

[Serializable]
public class ReportResultModel
{
    public ReportID reportID {get;set;}
    public List<MetricResultModel> Results { get; set; }
}

[Serializable]
public class MetricResultModel
{
    public Guid MetricGuid { get; set; }
    public int Value { get; set; }

    public MetricResultModel(MetricResultModel other)
    {
        MetricGuid = other.MetricGuid;
        Value = other.Value;
    }

    public MetricResultModel(Guid MetricGuid, int Value)
    {
        this.MetricGuid = MetricGuid;
        this.Value = Value;
    }

}

[Serializable]
public struct ReportID
{
    public Guid _topologyGuid;
    public Guid _matchGuid;
}

知道为什么数据没有到达吗? 任何帮助将不胜感激...

P.S。出于某种原因,我似乎无法在 fiddler 上捕捉到 http POST 消息,不知道为什么会这样。

尝试在控制器的动作中使用“[FromBody]”参数。当你 post 数据传递给 body 时,不在 url.

[HttpPost]
public void MetricResultUpdate([FromBody] ReportResultModel result)
{
    //this does get called, but
    //all the guids in result are zero here :(
}

问题是双重的:

  1. 我需要像这样在 JSON post 中指定类型:

    HttpResponseMessage resp = client.PostAsJsonAsync<MetricResultModel>("Reports/MetricEngineReport/MetricResultUpdate", result.Results[0]).Result;
    
  2. 我的模型的组件没有默认构造函数,这是接收端 JSON 反序列化所必需的。

我刚刚遇到了同样的问题。使用默认的 PostAsJsonAsync 扩展方法时,似乎 content-length header 设置为 0,这导致服务器忽略请求 body。

我的解决方案是安装使用新 System.Text.Json 序列化程序的 System.Net.Http.Json nuget 包。

当您添加 using System.Net.Http.Json; 时,您应该能够正确使用有效的新扩展方法 PostAsJsonAsync(设置 content-length header)。

namespace System.Net.Http.Json
{
    public static class HttpClientJsonExtensions
    {
        public static Task<HttpResponseMessage> PostAsJsonAsync<TValue>(this HttpClient client, string? requestUri, TValue value, CancellationToken cancellationToken)
        {
            return client.PostAsJsonAsync(requestUri, value, null, cancellationToken);
        }

    }
}