如何使用ServiceStack结合自定义REST Api实现自定义ResponseStatus

时间:2016-07-08 09:15:50

标签: c# rest servicestack

我一直在使用新的ServiceStack API:

[Route("/me/login/")]
public class LoginRequest : IReturn<LoginResponse>
{
    public string password { get; internal set; }
    public string username { get; internal set; }
}

public class LoginResponse
{
    public string token { get; set; }
}

...

client.PostAsync(new LoginRequest { username = email, password = password });

但是,服务器是Django REST Api。因此,当我输入不正确的密码时,我得到以下回复:

{
    "non_field_errors": [
        "Unable to login with the given credentials."
    ]
}

如何利用新的ServiceStack API检索non_field_errors属性中的信息? (我应该覆盖什么?)

1 个答案:

答案 0 :(得分:2)

ServiceStack服务客户端仅用于ServiceStack服务,我建议使用ServiceStack's HTTP Utils来呼叫第三方服务。

与JSON匹配的Response DTO如下所示:

public class LoginResponse
{
    public string token { get; set; }
    public string[] non_field_errors { get; set; }
}

如果响应返回非200 HTTP错误,则需要从错误正文响应中读取JSON,例如:

try 
{
    var response = baseUrl.CombineWith("me/login")
        .PostJsonToUrl(new LoginRequest { ... })
        .FromJson<LoginResponse>();
} 
catch (Exception ex) 
{
    HttpStatusCode? errorStatus = ex.GetStatus();
    string errorBody = ex.GetResponseBody();
    var errorDto = errorBody.FromJson<LoginResponse>();
}