反序列化Generic <t>

时间:2016-04-24 10:46:39

标签: c# generics asp.net-web-api2 deserialization

我致力于从Web API获得一致的响应。我正在通过API控制器操作方法

发送的ApiResponsDTO中包装所需的对象/实体
public IHttpActionResult Validate([FromBody] PortalLoginDTO logindDTO)
{
    IHttpActionResult response = null;
    ApiResponseDTO<AppUserDTO> responseData = null;

    var user = _userservice.GetUserByName(logindDTO.Username);
    responseData = new ApiResponseDTO<AppUserDTO>(user, 200);
    response = new ApiResponseActionResult<ApiResponseDTO<AppUserDTO>>(responseData, 200);

    return response;
}

API中的响应类

public class ApiResponseDTO<T>
{
    private T _value;

    [DataMember]
    public string Version { private set { } get { return "1.2.3"; ; } }

    [DataMember]
    public double StatusCode { get; set; }

    [DataMember]
    public List<string> ErrorMessages { get; set; }

    [DataMember]
    public T Result { private set { } get { return _value; } }
    public ApiResponseDTO()
    {
        ErrorMessages = new List<string>();
    }
    public ApiResponseDTO(T value, double statusCode)
    {
        StatusCode = (int)statusCode;
        _value = value;
        ErrorMessages = new List<string>();
    }
}

在上面的类的结果字段中,我想发送另一个请求的对象/类

请求的课程

[DataContract]
public partial class AppUserDTO
{
    public AppUserDTO()
    {

    }
    [DataMember]
    public int UserId { get; set; }
    [DataMember]
    public string Username { get; set; }
    [DataMember]
    public Nullable<int> TitleId { get; set; }
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string Surname { get; set; }
    [DataMember]
    public bool IsActive { get; set; }
    [DataMember]
    public string PasswordEncoded { get; set; }

}

在客户端MVC应用程序上,我正在使用javascriptserializer

var responsedatda = serializer.Deserialize<ApiResponseDTO<AppUserDTO>>(response.Content.ReadAsStringAsync().Result);

我收到了ApiResponseDTO但是请求的类没有被序列化,如图Response in client side中所示

我在API响应中没有获得嵌套UserDTO的原因是什么。

2 个答案:

答案 0 :(得分:1)

序列化程序需要能够设置结果的基础值,但是你的代码......

public T Result { private set { } get { return _value; } }

...不允许这样做,因为序列化程序使用默认构造函数创建类。

您需要更新Result属性...

public T Result { 
    get { return _value; } 
    set { _value = value; } 
}

或者你可以重构这个课程......

public class ApiResponseDTO<T> {

    [DataMember]
    public string Version { get { return "1.2.3"; } }

    [DataMember]
    public double StatusCode { get; set; }

    [DataMember]
    public List<string> ErrorMessages { get; set; }

    [DataMember]
    public T Result { get; set; }

    public ApiResponseDTO()
    {
        ErrorMessages = new List<string>();
    }

    public ApiResponseDTO(T value, double statusCode)
    {
        StatusCode = (int)statusCode;
        Result = value;
        ErrorMessages = new List<string>();
    }
}

答案 1 :(得分:0)