Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid calling ModelState.IsValid on every PostBack?

I pretty much always want to check if ModelSate.IsValid is called when I do a postback. And having to check at the start of every post back violates the DRY principle, is there a way to have it checked automatically?

Example:

[HttpPost("RegisterUser")]
[AllowAnonymous]
public async Task<IActionResult> RegisterUser([FromBody] UserRegisterViewModel vmodel)
{
    if(!ModelState.IsValid)          // This code is repeated at every postback
        return ModelInvalidAction(); // Is there a way to avoid having to write it down?

    // do other things

    return StatusCode(201);
}
like image 414
NomenNescio Avatar asked Aug 29 '26 09:08

NomenNescio


2 Answers

The framework provides an abstract ActionFilterAttribute that you can subclass.

You can use an action filter to automatically validate model state and return any errors if the state is invalid:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            context.Result = new BadRequestObjectResult(context.ModelState);
        }
    }
}

You can either then use it on individual actions or register it globally

Reference Asp.Net Core : Action Filters

like image 103
Nkosi Avatar answered Aug 31 '26 01:08

Nkosi


You can try something like this:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.ModelState.IsValid)
        {
            filterContext.Result = new BadRequestResult();
        }
    }
}

You can request any registered service like this filterContext.HttpContext.RequestServices.GetService<ILogger>(). You can decorate by action filter your action or controller:

[HttpPost("RegisterUser")]
[AllowAnonymous]
[ValidateModel]
public async Task<IActionResult> RegisterUser([FromBody] UserRegisterViewModel vmodel)
{
    ...
}
like image 22
AlbertK Avatar answered Aug 31 '26 00:08

AlbertK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!