Peter Kellner
Peter Kellner

Reputation: 15478

How To create a default ActionFilter (OnActionExecuting) and override with attribute

Using ASP.NET MVC4, I want to create an action filter attribute like this:

public class ForceHttps : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {...

What I want is, to assign that attribute to controllers that I want HTTPS, and for all others, I want to have another OnActionExecuting that forces HTTP.

I could decorate every other controller with [ForceNoHttps] and that would work, but my preference is to have the default be [ForceNoHttps], and only when I specify [ForceHttps] does this method get executed and not the other one.

So, I want it to execute one or the other, not both. That is,

if {[ForceHttps] is on controller}
  Force the page to https
else
  Force the page to http

Make sense? Can I do this?

Upvotes: 2

Views: 3237

Answers (1)

Dave Alperovich
Dave Alperovich

Reputation: 32490

I think what you want is something like this:

public class NotHttpsAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (request.IsSecureConnection)
        {
            string redirectUrl = filterContext.HttpContext.
                 Request.Url.ToString().Replace("https:", "http:");
            filterContext.HttpContext.Response.Redirect(redirectUrl);
        }
        base.OnActionExecuting(filterContext);
    }
}

The problem here is that you have to apply this filter to every Controller/Action that is NOT https.

A way to lessen your programming burden, is to make NotHttps into a global filter by registering it in your global.asax.

public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
    filters.Add(new NotHttpsAttribute()  { Order = 0 });
}

Upvotes: 1

Related Questions