Asp net core 웹 API, 모델 유효성 검사기에 대한 사용자 지정 응답을 반환하려고합니다. 그러나 ValidateModelFilter는 요청이 아닌 필수 필드 일 때 호출되지 않습니다.
ValidateModelFilter.cs
public class ValidateModelFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var response = new Model
{
error = context.ModelState.ToString()
};
context.Result = new BadRequestObjectResult(response);
}
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.Filters.Add(typeof(ValidateModelFilter)));
}
나는 이와 같은 응답을 받고있다
{
"errors": {
"Firstname": [
"The Firstname field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|e6752549-4142e91f1074e978."
}
다음과 같은 응답을 반환하고 싶습니다.
{
"error": "The Firstname field is required."
}
링크는 400 오류를 반환하고 파이프 라인을 단락시키는 기본 모델 바인딩 예외 필터를 비활성화하는 방법을 보여줍니다. 그래야만 사용자 지정 ActionFilterAttribute의 OnActionExecuting 메서드가 실제로 실행됩니다. 그러면 모든 것이 예상대로 작동합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다