ASP.NET MVC Action Filter Redirect Loop
I am seeing a redirect loop from our production servers when we enable the following attribute on a controller class:
public class TestRedirectHttpsAttribute : RedirectHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (Convert.ToBoolean(ConfigurationManager.AppSettings["TestSecureEnabled"] ?? bool.FalseString))
{
base.OnAuthorization(filterContext);
}
}
}
public class RedirectHttpsAttribute : FilterAttribute, IAuthorizationFilter
{
public virtual void OnAuthorization(AuthorizationContext filterContext)
开发者_StackOverflow中文版 {
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (!filterContext.HttpContext.Request.IsSecureConnection)
{
UriBuilder uriBuilder = new UriBuilder(filterContext.HttpContext.Request.Url);
uriBuilder.Scheme = "https";
uriBuilder.Port = -1; // Don't inject port
filterContext.Result = new RedirectResult(uriBuilder.ToString());
}
}
}
I know this is similar to the question - Redirect loop with SSL action filter in ASP.NET MVC but it was asked in February and I was hoping someone might have a better solution. The solution for the question in the link was to redirect from an action in the controller but if we want to redirect all actions to HTTPS we would have to make sure it was called in each rather than applying a custom FilterAttribute to the controller.
Note: This code works from our development environments using dummy SSL certs.
I may have got the wrong end of the stick and should be doing something else entirely, if so please accept my apologies.
For anyone that might have the same issue. It was the result of our load balancer handling SSL requests and handing off to our web servers using port 80; this resulted in not being able to identify that a secure request was indeed secure.
精彩评论