在ASP.NET WEB API调用上发布登录信息时出错

本文关键字:登录 信息 出错 布登录 NET ASP WEB API 调用 | 更新日期: 2023-09-27 18:20:05

我在尝试对ASP.NET Web API进行后期调用时遇到此异常。我从Windows通用应用程序调用这个:

类型'<>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));
    }

在ASP.NET WEB API调用上发布登录信息时出错

最好的猜测是,您收到这个错误是因为您使用的序列化程序不支持匿名类型。我建议您尝试使用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);
}

我找到了解决方案。我将post数据更新为键值对,它起到了作用。

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