来自身份注册格式的JSON响应



我已经为WebApi项目添加了流畅的验证,它运行良好,我得到了以下JSON响应作为用户注册的示例:

{
"errors": {
"Email": [
"'Email' is not a valid email address."
],
"Password": [
"'Password' must contain at least one uppercase, lowercase, number and symbol"
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "8000003d-0000-fc00-b63f-84710c7967bb"
}

如果用户电子邮件已经存在,我将添加验证。错误响应的格式非常不同,我需要相同的格式来在客户端捕获错误。

错误模型类别:

public class ErrorResponse
{
public List<ErrorModel> Errors { get; set; } = new List<ErrorModel>();
}
public class ErrorModel
{
public string FieldName { get; set; }
public string Message { get; set; }
}

寄存器控制器:

var authResponse = await _identityService.RegisterAsync(request);
if (!authResponse.Success)
{
var errorResponse = new ErrorResponse();
var errorModel = new ErrorModel
{
FieldName = "User",
Message = "A user exists"
};
errorResponse.Errors.Add(errorModel);

return BadRequest(errorResponse);
}

JSON响应:

{
"errors": [
{
"fieldName": "User",
"message": "A user exists"
}
]
}

您可以使用字典来实现这一点:

public class ErrorResponse
{
public Dictionary<string,List<string>> Errors { get; set; } = new Dictionary<string,List<string>>();
}

并添加这样的值:

errorResponse.Add("User",new List<string>{"A user exists"});

相关内容

  • 没有找到相关文章

最新更新