2016-04-24 86 views
1

我致力於從API獲得一致的響應。我包裹經由API控制器操作方法發送反序列化通用<T>

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

響應類所需的對象/在ApiResponsDTO實體在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

回答

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