我在嘗試在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));
}
您也可以嘗試在發送到API之前手動序列化您的數據 – Andrew