i'hv written my own action filter and registered in global.asax file, now my problem is how do i skip
this filter for specific actions, i thought about this by creating a custom attribute for e.g DontValidate
and place it over the action for which i want to skip the validation, and in my action filter code i'll put a condition that if the action contains
DontValidate
attribute then skip the validation. So currently i'm not getting how to
implement it:
below code is my validation action filter
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.Request.Method.ToString() == "OPTIONS") return;
//bool dontValidate = context.ActionDescriptor. // here im stuck how to do
var modelState = context.ModelState;
if (!modelState.IsValid)
{
JsonValue errors = new JsonObject();
foreach (var key in modelState.Keys)
{
// some stuff
}
context.Response = context.Request.CreateResponse<JsonValue>(HttpStatusCode.BadRequest, errors);
}
}
}
In Listing 1, a single action filter – the OutputCache action filter – is applied to the Index() method. If you need, you can apply multiple action filters to the same action. For example, you might want to apply both the OutputCache and HandleError action filters to the same action.
Filters execute in this order: Authorization filters. Action filters. Response/Result filters.
You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Result property to a non-null value.
The main difference between them is their scope. Filters are a part of MVC, so they are scoped entirely to the MVC middleware. Middleware only has access to the HttpContext and anything added by preceding middleware.
You could get the list of attributes that were used to decorate the controller action from the ActionDescriptor
property of the context:
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
if (context.ActionDescriptor.GetCustomAttributes<DontValidateAttribute>().Any())
{
// The controller action is decorated with the [DontValidate]
// custom attribute => don't do anything.
return;
}
if (context.Request.Method.ToString() == "OPTIONS") return;
var modelState = context.ModelState;
if (!modelState.IsValid)
{
JsonValue errors = new JsonObject();
foreach (var key in modelState.Keys)
{
// some stuff
}
context.Response = context.Request.CreateResponse<JsonValue>(HttpStatusCode.BadRequest, errors);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With