简体   繁体   中英

ReadAsAsync cast custom class return null for .net core

I have a old MVC program, converting to .net core. but I am facing ReadAsAsync() casting issue. Same code worked on old MVC, but not .NET Core.

I have a User model:

public class User
{
    public int Id { get; set; }

    public string Username { get; set; }

    public string Password { get; set; }

    public int Status { get; set; }

    public string Address { get; set; }
}

I try test the result by use the following code to get the wep api HttpResponseMessage:

string responseContent = await content.ReadAsStringAsync();

And successful return following User data:

{"id":1, "username":"howard","password":"xxxxx","status":1,"Address":null} 

When I cast the response to User model use code below, is working find and return User model.

//worked
var data = await content?.ReadAsAsync<User>();

在此处输入图像描述

But when I added a custom ApiResult class, it's become not working, and return null for "result" property in ApiResult class.

//not work
var data = await content?.ReadAsAsync<ApiResult<User>>()

在此处输入图像描述

But it's worked on old MVC:

在此处输入图像描述

My ApiResult class:

public class ApiResult
{
    public bool CustomizedisSuccess { get; set; }

    public string CustomizedErrorMsg { get; set; }

    public static ApiResult<T> Success<T>(T result = default(T))
    {
        return new ApiResult<T>
        {
            Result = result,
            CustomizedisSuccess = true,
            CustomizedErrorMsg = "Error"
        };
    }
}

public class ApiResult<T> : ApiResult
{
    public T Result { get; set; }
}

The result always return null, by right suppose cast to User model. Same code worked in previous MVC but not .NET Core.

Deserialize it as a User (because that is what the JSON is) and embed it in an ApiResult afterward. Looks like you already have a helper method for it.

var user = await content?.ReadAsAsync<User>();
var data = ApiResult.Success(user);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM