HttpClient.PostAsJsonAsync 内容为空

Jap*_*s55 1 asp.net-mvc json dotnet-httpclient

我正在尝试使用 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我的模型有点复杂:

[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;
}
Run Code Online (Sandbox Code Playgroud)

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

PS 由于某种原因,我似乎无法在 fiddler 上捕获 http POST 消息,不知道为什么会这样。

小智 6

尝试在控制器的操作中使用“[FromBody]”参数。当您发布数据时,数据将传递到正文而不是网址中。

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