ASP.NET MVC - RequireHttps - Specify a redirect URL
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.
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.
精彩评论