Generally,
whenever something is to be saved to the database or to any other place, as a
best practice almost everyone use to validate the state of the model. So, if
state of model is valid, we proceed and if model state is invalid, we handle it
as a bad request. This looks something like this:
Next is to
update ConfigureServices method under Startup class:
If(!ModelState.IsValid)
{
// create bad request object
}
So, all
these were done by using the IsValid property.
Problem
Now what if
we have to perform the same validation for all the models. Are we going to
write the same validation in each and every controller?
Of course, No.
Solution
Rather than
duplicating the same code in each and every controller, we can create a global
filter. This global filter has few methods, but for our purpose we can go with
OnActionExecuting.
public class ValidateModelStateFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
services.AddMvcCore(options =>
{
options.Filters.Add(typeof(ValidateModelFilter));
})
Once above
changes are done, we need not to repeat the same ModelState validation check in
each and every controller.
Hope this tip would be useful.
먹튀사이트 잡는 고릴라의 먹튀검증 통과 메이저토토사이트 안전놀이터 추천 훌륭한 먹튀검증을 통한 안전토토사이트를 추천합니다 고릴라만의 검증 시스템은 특별합니다 전세계적인 먹튀검증을 인전받은 최고의 메이저사이트 추천을 합니다 자세한 내용은 내 웹 사이트를 방문하십시오 먹튀검증.
ReplyDelete당신은 훌륭한 일을 해냈습니다. 앞으로 더 많은 정보를 얻기 위해 많은 타자를 할 수 있기를 바랍니다 여기를 클릭하십시오 메이저사이트.
ReplyDelete