2013-02-09 105 views
6

我有一個項目使用MVC4,我想問如何從webapi獲取數據並返回視圖。如何在控制器中調用web api並返回視圖MVC4

型號

public class Name 
{ 
    public Int32 NameId { get; set; } 
    public String FirstName{ get; set; } 
    public String LastName{ get; set; } 
    public String CreatedBy { get; set; } 
} 

public class IListMyProject 
{ 
    public List<Name> Names { get; set; } 
} 

我可以使用此代碼

public ActionResult Index() 
    { 
     string securityToken = repo.GetTokens(); 
     if (securityToken != null) 
     { 
      HttpClient client = new HttpClient(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "webapiurl/api/Name/Get?$orderby=LastName&$top=10"); 
      string authHeader = System.Net.HttpRequestHeader.Authorization.ToString(); 
      httpRequestMessage.Headers.Add(authHeader, string.Format("JWT {0}", securityToken)); 
      var response = client.SendAsync(httpRequestMessage) 
       .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode()) 
       .Result; 
      if (response.IsSuccessStatusCode) 
      { 
       model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList(); 

      } 
     } 
     return View("Index", model); 
    } 

我能回到我的觀點列出所有在我Index.cshtml。現在我有一個名爲Details.cshtml另一種觀點與此代碼:

public ActionResult Details(string id) 
    { 
     string securityToken = repo.GetTokens(); 
     if (securityToken != null) 
     { 
      HttpClient client = new HttpClient(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "webapiurl/api/Name/GetById/"+id+""); 
      string authHeader = System.Net.HttpRequestHeader.Authorization.ToString(); 
      httpRequestMessage.Headers.Add(authHeader, string.Format("JWT {0}", securityToken)); 

      var response = client.SendAsync(httpRequestMessage) 
       .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode()) 
       .Result; 
      if (response.IsSuccessStatusCode) 
      { 

       model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList(); 

      } 
     } 
     return View(model); 
    } 

對於這個細節,我的Json如下:

application/json, text/json 
{ 
    "NameId": 1, 
    "FirstName": "This is First Name", 
    "LastName": "This is Last Name", 
    "CreatedBy": "This is Created By" 
} 

當我運行它,我得到這個錯誤:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[Models.Name]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. 

Path 'NameId', line 1, position 10. 

我該如何解決這個問題,即時通訊新的webapi。我想知道爲什麼如果我列出所有(對於索引,我使用api/get)它的工作原理,但是當我想詳細顯示它時,它不起作用。

感謝幫助

問候

編輯

,當我在

model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList(); 

其說空調試,有什麼不對,當我嘗試得到的迴應?

回答

3

的問題是:

{ 
    "NameId": 1, 
    "FirstName": "This is First Name", 
    "LastName": "This is Last Name", 
    "CreatedBy": "This is Created By" 
} 

不能反序列化一個IList。上面的JSON只是一個名稱,而不是一個名稱集合。所以Json.NET反序列化將失敗。

確保您的Web API控制器返回IList,或者更改您的MVC代碼以將內容作爲單個名稱讀取。在JSON名稱的集合是這樣的,而不是:

[{ 
    "NameId": 1, 
    "FirstName": "This is First Name", 
    "LastName": "This is Last Name", 
    "CreatedBy": "This is Created By" 
}, 
{ 
    "NameId": 2, 
    "FirstName": "This is First Name", 
    "LastName": "This is Last Name", 
    "CreatedBy": "This is Created By" 
}] 
+0

我認爲這是我的問題。但我不做webapi,我只是在我的mvc中使用它。如何列出該json?感謝bro – 2013-02-09 04:37:06

+1

,然後讀取內容作爲名稱,而不是IList 如果您不控制Web服務... – 2013-02-09 04:46:52

+0

我使用 var NamesId = response.Content.ReadAsAsync ().Result; 當我調試NamesId,我可以得到結果。但我怎麼能返回到Details.cshtml視圖? – 2013-02-09 04:48:06

1

在Web API將返回類型的單個對象名稱名稱不是一個集合。我沒有看到你在哪裏定義型號。我添加了類型的定義名稱。嘗試這個。

public ActionResult Details(string id) 
{ 
    string securityToken = repo.GetTokens(); 
    Name model; 
    if (securityToken != null) 
    { 
     HttpClient client = new HttpClient(); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

     HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "webapiurl/api/Name/GetById/"+id+""); 
     string authHeader = System.Net.HttpRequestHeader.Authorization.ToString(); 
     httpRequestMessage.Headers.Add(authHeader, string.Format("JWT {0}", securityToken)); 

     var response = client.SendAsync(httpRequestMessage) 
      .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode()) 
      .Result; 
     if (response.IsSuccessStatusCode) 
     { 

      model = response.Content.ReadAsAsync<Name>(); 

     } 
    } 
    return View(model); 
} 
+0

你好,我試試這個,結果是「值不能爲空」。 – 2013-02-13 02:27:33

+0

對不起,我不明白原來的問題。看看我更新的答案,看看是否有幫助。 – 2013-02-13 13:37:17

1

這個問題似乎是,你的JSON,而你正在閱讀的結果作爲IList<Name>只返回1記錄的事實。將其更改爲只需Name即可解決問題。

但是你的問題是:「如何調用在控制器的網絡API,並返回到圖MVC4

我建議你看看http://restsharp.org/您可以簡化代碼:

public ActionResult Details(string id) 
{ 
    string securityToken = repo.GetTokens(); 
    Name model; 
    if (securityToken != null) 
    { 
     var client = new RestClient(""); 

     var request = new RestRequest("webapiurl/api/Name/GetById/"+id, HttpMethod.Get); 
     string authHeader = System.Net.HttpRequestHeader.Authorization.ToString(); 
     request.AddHeader(authHeader, string.Format("JWT {0}", securityToken)); 

     var model = client.Execute<Name>(request); 
    } 
    return View(model); 
} 
相關問題