【发布时间】:2021-07-20 20:38:01
【问题描述】:
我正在使用 ASP.NET Core 5.0,并且我有带有 Register 方法的用户控制器,它接收 UserRegisterInputModel。问题是我的 API 的所有响应都是特定格式的,但是 ApiController 会自动验证输入模型并以另一种格式返回 BadResponse。
这是我的抽象响应模型
public abstract class ResponseModel
{
public ResponseModel(bool successfull, int statusCode)
{
this.Successfull = successfull;
this.StatusCode = statusCode;
this.ErrorMessages = new List<string>();
}
public bool Successfull { get; set; }
public int StatusCode { get; set; }
public List<string> ErrorMessages { get; set; }
public object Data { get; set; }
}
这是我的 BadResponseModel
public class BadResponseModel : ResponseModel
{
public BadResponseModel()
: base(false, 400)
{
}
}
这是我在用户控制器中注册方法的一部分。
[HttpPost]
public async Task<IActionResult> Register(UserRegisterInputModel input)
{
if (!ModelState.IsValid)
{
return Json(new BadResponseModel()
{
ErrorMessages = new List<string>()
{
"Invalid register information"
}
});
}
ApiController 功能会自动验证我的模型,并且永远不会到达 BadResponseModel 的返回语句。有什么方法可以停止自动验证或更改 ApiController 验证的默认响应?
【问题讨论】:
-
我认为这篇文章已经回答了你的问题。 check this out
-
您可以使用
InvalidModelStateResponseFactory生成自定义回复。检查以下链接:I need to return customized validation result (response) in validation attributes in ASP.Net core Web API 和 Handling validation responses for ASP.NET Core Web API。
标签: c# api asp.net-core asp.net-web-api