Ropstah
Ropstah

Reputation: 17794

.NET-MVC - Rewrite URL's + certain URL's through SSL?

I have a webserver running IIS 6, .NET MVC with a single domainname. The site uses URL rewriting to produce URLs like:

domain.com/controller/action

I would like to force one (1) controller to use SSL (others should work without SSL). How should I implement this?

Upvotes: 4

Views: 473

Answers (2)

tvanfosson
tvanfosson

Reputation: 532435

Decorate the controller that needs SSL with the RequireHttpsAttribute.

[RequireHttps]
public class SecureController : Controller
{
   ...
}

Although, you may prefer a custom version that ignores this for requests from localhost if you are using Cassini for debugging.

[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public class RemoteRedirectToHttpsAttribute : RequireHttpsAttribute
{
    public override void OnAuthorization( AuthorizationContext filterContext )
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException( "filterContext" );
        }

        if (filterContext.HttpContext != null && (filterContext.HttpContext.Request.IsLocal || filterContext.HttpContext.Request.IsSecureConnection))
        {
            return;
        }

        filterContext.Result = new RedirectResult( filterContext.HttpContext.Request.Url.ToString().Replace( "http:", "https:" ) );
    }
}

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You could annotate controllers that require SSL with the RequireHttps attribute or make them derive from a base controller that's marked with this attribute.

Upvotes: 0

Related Questions