2015-11-02 53 views
0

我在嘗試在ASP.NET Web API上進行調用時遇到此異常。我從一個Windows通用應用程序調用此:在ASP.NET WEB API調用上發佈登錄信息時發生錯誤

類型 '<> f__AnonymousType0`3 [System.String,System.String,System.String]' 無法序列。考慮用 DataContractAttribute屬性標記它。

這裏是我的代碼:

var loginData = new { grant_type = "password", username = name, password = pass }; 
    var queryString = "grant_type = password, username = " + name + ", password = " + pass; 

    HttpClient httpClient = new HttpClient(); 
    try 
    { 
     string resourceAddress = "http://localhost:24721/Token"; 
     //int age = Convert.ToInt32(this.Agetxt.Text); 
     //if (age > 120 || age < 0) 
     //{ 
     // throw new Exception("Age must be between 0 and 120"); 
     //} 

     string postBody = Serialize(loginData); 
     httpClient.DefaultRequestHeaders.Accept.Add(
      new MediaTypeWithQualityHeaderValue("application/json")); 
     HttpResponseMessage wcfResponse = await httpClient.PostAsync(resourceAddress, 
      new StringContent(queryString, Encoding.UTF8)); 
    } 

回答

0

我找到了解決辦法。我將發佈數據更新爲關鍵值對,並且工作正常。

using (var client = new HttpClient()) 
     { 
      string resourceAddress = "http://localhost:24721/Token"; 
      var requestParams = new List<KeyValuePair<string, string>> 
      { 
       new KeyValuePair<string, string>("grant_type", "password"), 
       new KeyValuePair<string, string>("username", name), 
       new KeyValuePair<string, string>("password", pass) 
      }; 
      var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams); 
      var tokenServiceResponse = await client.PostAsync(resourceAddress, requestParamsFormUrlEncoded); 
      var responseString = await tokenServiceResponse.Content.ReadAsStringAsync(); 
      var responseCode = tokenServiceResponse.StatusCode; 
      var responseMsg = new HttpResponseMessage(responseCode) 
      { 
       Content = new StringContent(responseString, Encoding.UTF8, "application/json") 
      }; 
      return responseMsg; 
     } 
+0

您也可以嘗試在發送到API之前手動序列化您的數據 – Andrew

0

最好的猜測是,你得到的錯誤,因爲你使用的串行不支持匿名類型。我會建議嘗試使用Json.Net,它很好地處理它們。我相信你可以從NuGet中包含它。

如果在您的項目中引用該庫,那麼你可以修改代碼如下所示:

var loginData = new { grant_type = "password", username = name, password = pass }; 

HttpClient httpClient = new HttpClient(); 
try 
{ 
    string resourceAddress = "http://localhost:24721/Token"; 

    string postBody = Newtonsoft.Json.JsonConvert.SerializeObjectloginData); 
    var content = new StringContent(postBody, Encoding.UTF8, "application/json"); 
    httpClient.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/json")); 
    HttpResponseMessage wcfResponse = await httpClient.PostAsync(resourceAddress, content); 
} 
相關問題