gpt4 book ai didi

c# - 如何结合使用 ServiceStack 和自定义 REST Api 来实现自定义 ResponseStatus

转载 作者:行者123 更新时间:2023-11-30 23:23:40 25 4
gpt4 key购买 nike

我一直在像这样使用新的 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 属性中的信息? (我应该覆盖什么?)

最佳答案

ServiceStack 服务客户端仅用于 ServiceStack 服务,我建议使用 ServiceStack's HTTP Utils用于调用第 3 方服务。

匹配该 JSON 的响应 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>();
}

关于c# - 如何结合使用 ServiceStack 和自定义 REST Api 来实现自定义 ResponseStatus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38263020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com