.net 코어 2.x 프로젝트에서 작동하는 임. 각 동작에 코드 아래에 작성하여 내 모델 상태를 확인합니다..net core 컨트롤러/동작에서 ModelState를 반복하지 마십시오.
if (ModelState.IsValid)
{
// Do something
}
else
{
// Return Modelstate Error
}
각 작업에서 조건을 반복하지 않는 것이 가장 좋은 방법인지 알고 싶습니다. 작업에 도달하기 전에 modelstate의 유효성을 검사하고 modelstate가 유효하지 않은 경우 적절한 오류 메시지를 반환하고 싶습니다.
업데이트
참고. 내 작업은 단순한 API 작업이며 HttpContext 본문에 문자열 배열 형식의 오류 (내 모델에 있음)를 반환하고자합니다.
예 : 모델 속성.
[Required(ErrorMessage = "Fill the name Please !!!")]
public string FirstName { get; set; }
예 : 조치. 이
public class ModelStateValidationFilter : ActionFilterAttribute
{
public string ErrorPage;
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
//return error result
List<string> list = (from modelState in context.ModelState.Values from error in modelState.Errors select error.ErrorMessage).ToList();
context.Result = new BadRequestObjectResult(list);
//or redirect to some result
context.Result = new RedirectToRouteResult(ErrorPage);
//or do whatever you need
}
base.OnActionExecuting(context);
}
}
같은
[HttpPost]
public void Create([FromBody]MyModel model)
{
if (ModelState.IsValid)
{
// Do something
}
else
{
// Return Modelstate Error
}
}
이것을 확인해보십시오. https://www.jerriepelser.com/blog/validation-response-aspnet-core-webapi/ –