gpt4 book ai didi

c# - WebAPI 返回类型

转载 作者:太空狗 更新时间:2023-10-30 01:31:33 25 4
gpt4 key购买 nike

我是否应该始终返回相同的 JSON 解析对象

示例:

在网站上,用户输入他的用户名和密码。

当用户按下提交时,他会向/api/logintest/{key} 发送请求。如果用户和密码匹配,此 URL 调用的方法是否应该返回一个 JSON 对象,例如 {errMsg: null},如果不匹配则返回 {errMsg: "bad username or password"};或者,如果用户详细信息不匹配,我应该返回错误消息,如果找到用户,我应该返回 JSON 中的用户对象吗?

这是我的代码

    [ResponseType(typeof(User))]
[HttpPost]
[Route("api/logintest/{key}")]
public IHttpActionResult LoginTest(LoginForm luser , String key)
{
//test the api key
if(key == "jordanisthebest")
{
//we try to get the user by his username and password
User userReturn = UsersManager.getUserByEmailAndPassword(new User { Email = luser.Email, Password = luser.Password });

//if the user is null then we return the err message
if (userReturn == null)
ModelState.AddModelError("Email", "Bad email or password");

//if model state is not good we send err msg
if (!ModelState.IsValid)
return Ok(ModelState.getListErrorAndKey(null, typeof(LoginForm)));

//if all good we return the user
return Ok(userReturn);
}

return NotFound();
}

最佳答案

如果你想知道他们是否进行了身份验证,那么你可以返回:

{ "authenticated" : true } // or false

如果想知道原因,可以记录或显示:

{ "authenticated": false, "reason" : "User account was locked" }

为了更加 RESTful,您可以制定路线:

GET /api/users/{userName}/authenticate

您的“快乐之路”将返回 HTTP 状态 200 和 JSON 消息作为响应内容。

如果未找到用户(因为 API 调用正在寻找用户资源),您可以返回 404 未找到的 HTTP 状态代码,但不需要返回 401 的 HTTP 状态代码,因为资源本身不是调用者无权使用的东西。

最好不要向用户公开他们为什么特别未能通过身份验证。您返回给用户的信息越多,黑客的信息就越多,他们甚至可能不知道自己是否拥有有效的用户帐户。

关于c# - WebAPI 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40837268/

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