HttpClient.PostAsJsonAsync内容为空 [英] HttpClient.PostAsJsonAsync content empty

查看:0
本文介绍了HttpClient.PostAsJsonAsync内容为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的发送方:

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.
    }
}

我的接收端在不同的类中,在本地计算机上的不同进程中运行:

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;
}

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

附言。由于某种原因,我似乎无法在Figdler上捕捉到http POST消息,不确定是什么原因。

推荐答案

问题是双重的:

  1. 我需要在JSON帖子中指定类型,如下所示:

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

这篇关于HttpClient.PostAsJsonAsync内容为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆