ReadAsAsync cast custom class return null for .net core

862 Views Asked by At

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 message.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 message.Content?.ReadAsAsync<User>();

enter image description here

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 message.Content?.ReadAsAsync<ApiResult<User>>()

enter image description here

But it's worked on old MVC:

enter image description here

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.

Update:

I am tried use ReadFromJsonAsync, but it's not working, also return null.

// not work also
var result = await message.Content.ReadFromJsonAsync<ApiResult<User>>();

same case with me:

HttpContent.ReadFromJsonAsync Won't Deserialize Generic Object (Blazor WebAssembly)

https://github.com/dotnet/aspnetcore/issues/21030

1

There are 1 best solutions below

4
John Wu On

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