JsonSerializationException:无法创建和填充列表类型Parse.ParseUser

时间:2018-06-23 23:59:12

标签: c# asp.net-core

当我尝试登录并在会话中存储ParseUser复杂对象时,我得到一个JsonSerializationException。怎么了?

private const string CURRENT_USER_KEY = "CurrentUser";
private const string IS_USER_LOGGED_IN_KEY = "IsUserLoggedIn";

public ParseUser CurrentUser
{
    get => HttpContext.Session.GetObjectFromJson<ParseUser>(CURRENT_USER_KEY);
    set => HttpContext.Session.SetObjectAsJson(CURRENT_USER_KEY, value);
}

登录任务:

我通过前端的AJAX调用接收用户登录数据,然后开始解析登录调用。

// ----- Log In  -----

public async Task<JsonResult> OnPostLogin()
{

    MemoryStream stream = new MemoryStream();
    Request.Body.CopyTo(stream);
    stream.Position = 0;

    using (StreamReader reader = new StreamReader(stream))
    {
        string requestBody = reader.ReadToEnd();
        if (requestBody.Length > 0)
        {

            // Values from retrived JSON object
            var loginObject = JObject.Parse(requestBody);
            var username = loginObject["username"].ToString();
            var password = loginObject["password"].ToString();

            // Login in user
            CurrentUser =  await ParseUser.LogInAsync(username, password);
            IsUserLoggedIn = true;
        }
    }

    return new JsonResult("");
}

错误:

JsonSerializationException: Cannot create and populate list type Parse.ParseUser. Path '', line 1, position 1.

Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewList(JsonReader reader, JsonArrayContract contract, out bool createdFromNonDefaultCreator)

出现在:

Web.Pages.IndexModel.get_CurrentUser() in Index.cshtml.cs

                get => HttpContext.Session.GetObjectFromJson<ParseUser>(CURRENT_USER_KEY);

反序列化助手:

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace YeetClub.WebPlatform.Application.Utilities
{
    public static class SessionExtensions
    {
        public static void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObjectFromJson<T>(this ISession session, string key)
        {
            var value = session.GetString(key);

            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }
}

ParseUser类以供参考:

https://gist.github.com/SeloSlav/f74e5ae8f1cddca4cef62e0376fe9b05

0 个答案:

没有答案