客户端获取对web api方法的请求并获取一个对象作为响应问题是我无法取消此对象..
客户端方法,向web api发出get请求
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:57752");
HttpResponseMessage response = client.GetAsync("api/Auth/Login/" + user.Username + "/" + user.Password).Result;
JsonResult result = null;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsAsync<JsonResult>().Result;
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
User validUser = json_serializer.Deserialize<User>(result.Data.ToString());//Throws Exp.
}
我想简单地将这个从api返回的对象实例放到validUser ..
错误消息:
无法将“System.String”类型的对象转换为类型 'MongoDB.Bson.ObjectId'
这是模特:
public abstract class EntityBase
{
[BsonId]
public ObjectId Id { get; set; }
}
public class User : EntityBase
{
//public string _id { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
[DataType(DataType.Text)]
[Display(Name = "Username")]
public string Username { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
public void EncryptPassword()
{
Password = Encrypter.Encode(this.Password);
}
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
答案 0 :(得分:2)
你没有告诉反序列化器反序列化的内容。此
User validUser = (User)json_serializer.DeserializeObject(result.Data.ToString());
反序列化为一个对象,然后尝试将该对象强制转换为User
,这将失败。您需要使用通用方法:
User validUser = json_serializer.Deserialize<User>(result.Data.ToString());
如果JSON名称和类名称/结构不同Changing property names for serializing,则完全有可能需要做更多的工作。