2015-07-21 24 views
1

我想從一個進程發送一個複雜的數據類型到另一個使用ASP.net MVC。由於某種原因,接收端總是收到空白(零/默認)數據。HttpClient.PostAsJsonAsync內容爲空

我的發送方:

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

任何想法爲什麼數據沒有到達? 任何幫助將不勝感激...

P.S.由於某種原因,我似乎無法趕上小提琴手的HTTP POST消息,不知道爲什麼。

回答

1

嘗試在Controller的Action中使用「[FromBody]」參數。正如你發佈的數據傳遞給正文不在url中。

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

感謝幫助! –

1

的問題是雙重的:

  1. 我需要在我的JSON後指定類型是這樣的:

    HttpResponseMessage resp = client.PostAsJsonAsync<MetricResultModel>("Reports/MetricEngineReport/MetricResultUpdate", result.Results[0]).Result; 
    
  2. 沒有默認構造函數的我的組件模型,這對於接收端的JSON反序列化是必需的。

+0

謝謝。我一直在爲類似的東西奮鬥幾天,並且'1.'解決了它(已經有了默認的構造函數)。 – Jake