Ali
Ali

Reputation: 57

Filter not working for ASP.NET Core MVC project

I have a filter which is working fine with ASP.NET Core WebAPI for Model Validation on POST and PUT actions.

Question: I want to use it in Web MVC project. Can someone tell me what should I return from filter to make it work. Need to return ViewModel as well?

Returning context.ModelState not working.

Thanks

Filter Code

public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            if ((context.HttpContext.Request.Method == ("POST") | context.HttpContext.Request.Method == ("PUT")) && !context.ModelState.IsValid)
                context.Result = new BadRequestObjectResult(context.ModelState);
        }
    }

Upvotes: 1

Views: 756

Answers (1)

hozefam
hozefam

Reputation: 1040

Replace | with || in the if statment

if ((context.HttpContext.Request.Method == ("POST") || context.HttpContext.Request.Method == ("PUT")) && !context.ModelState.IsValid)

Upvotes: 3

Related Questions