2

I'm using [RequireHttps] in my MVC2 application, but in my testing machine the SSL url is different from the actual site url (it's a shared SSL enviroment).

Example: My site url is http://my-domain.com and the SSL url is https://my-domain.sharedssl.com.

Is there a way to tell MVC to redirect to that url when a controller/action requires HTTPS (preferably in the Web.config file)?

Thanks.

1
  • This sort of redirection is often handled at the load balancer level; you sure you need it in your application? Commented Nov 1, 2013 at 18:17

1 Answer 1

2

There isn't a way using the built-in RequireHttpsAttribute class, but writing your own MVC filter attributes is very easy. Something like this (based on the RequireHttpsAttribute class) ought to work:

public class RedirectToHttpsAttribute : FilterAttribute, IAuthorizationFilter 
{
    protected string Host
    {
        get;
        set;
    }

    public RedirectToHttpsAttribute ( string host ) 
    {
        this.Host = host;
    }

    public virtual void OnAuthorization(AuthorizationContext filterContext) 
    {
        if (filterContext == null) {
            throw new ArgumentNullException("filterContext");
        }

        if (!filterContext.HttpContext.Request.IsSecureConnection) {
            HandleHttpsRedirect(filterContext);
        }
    }

    protected virtual void HandleHttpsRedirect(AuthorizationContext context) 
    {
        if ( context.HttpContext.Request.HttpMethod != "GET" ) 
        {
            throw new InvalidOperationException("Can only redirect GET");
        }

        string url = "https://" + this.Host + context.HttpContext.Request.RawUrl;
        context.Result = new RedirectResult(url);
    }
}

EDIT:

I don't know for sure if you can read from web.config in a FilterAttribute, but I can't think of a reason why not.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool solution, but I don't it's worth in my case, since it's only for the testing server (in production we have my-domain.com). But thanks anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.