MyTested.AspNetCore.Mvc icon indicating copy to clipboard operation
MyTested.AspNetCore.Mvc copied to clipboard

Add option to execute action filters

Open ivaylokenov opened this issue 6 years ago • 3 comments

Example test:

MyController<HomeController>
    .Instance()
    .WithFilters(filters => filters
         .OnActionExecuting()
         .OnActionExecuted())
    .Calling(c => c.Index())
    .ShouldReturn()
    .Ok();

ivaylokenov avatar Jul 07 '19 12:07 ivaylokenov

This is great, would love to see that as I use filters to validate ModelState

manuelids avatar Aug 05 '19 16:08 manuelids

@manuelids Could you please provide the code you use in the action filter to validate the ModelState? Thank you!

ivaylokenov avatar Aug 07 '19 20:08 ivaylokenov

@manuelids Could you please provide the code you use in the action filter to validate the ModelState? Thank you!

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

This validationActionFilter returns a custom Object result that returns a BadRequest and displays all the validation errors per field.

Filter is registered at Startup

services.AddMvc().AddMvcOptions(o =>
{
    o.Filters.Add(new ValidationActionFilter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

Thanks much!

manuelids avatar Aug 09 '19 21:08 manuelids