由於某種原因,HttpCookie對象無法從JSON反序列化。我收到此錯誤 -從JSON反序列化HttpCookie對象
無法填充列表類型System.Web.HttpValueCollection。路徑「價值」,行..,位置..
我設法給JSON反序列化到一個自定義類(HttpCookieModel
),其不具有Values
屬性,然後重新從數據中的HttpCookie。 但是沒有更簡單的方法嗎?
using Newtonsoft.Json; // v7.0.1
public JsonResult GetCookie() {
return Json(new { Success = true, Username = model.UserName, Cookie = FormsAuthentication.GetAuthCookie(model.UserName, true) });
}
private static void DoSomeTests()
{
// HttpWebRequest request....
// Call GetCookie()
// ...
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream(), true))
{
res = streamReader.ReadToEnd();
}
// Deserialize
try
{
MyResponse mr = JsonConvert.DeserializeObject<MyResponse>(res);
}
catch (Exception ex)
{
string message = ex.Message; // message: Cannot populate list type System.Web.HttpValueCollection. Path 'Values'....
}
public class MyResponse
{
public bool Success { get; set; }
public string Username { get; set; }
// public HttpCookie Cookie { get; set; } // Problems deserializing Values collection.
public HttpCookieModel Cookie { get; set; }
}
// This model works - but is there a simpler way?
public class HttpCookieModel
{
public string Domain { get; set; }
public DateTime Expires { get; set; }
public bool HasKeys { get; set; }
public bool HttpOnly { get; set; }
public string Name { get; set; }
public string Path { get; set; }
public bool Secure { get; set; }
public bool Shareable { get; set; }
public string Value { get; set; }
public HttpCookie ConvertToHttpCookie()
{
HttpCookie result = new HttpCookie(this.Name);
result.Domain = this.Domain;
result.Expires = this.Expires;
result.HttpOnly = this.HttpOnly;
result.Path = this.Path;
result.Secure = this.Secure;
result.Shareable = this.Shareable;
result.Value = this.Value;
return result;
}
}
}
我已經創建了這個類 - 但它是我不想使用該解決方案。 HttpCookie是一個C#類,不是一個自定義類,但DeserializeObject不能反序列化,我不知道爲什麼。 – TamarG