我致力於從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
。