Hi All,
Can someone verify the integrity of this chunk of code? I want to decorate the controllers with it so that it will normalize the url to either https and/or www. This is my second rewrite of the code because the first one tossed itself into an infinite redirect, but somehow I still think it's not quite there...
public class NormalizeUrl : ActionFilterAttribute {
private bool ForceHttps = false;
private bool ForceWww = false;
public NormalizeUrl() {
}
public NormalizeUrl(
bool ForceHttps,
bool ForceWww) {
this.ForceHttps = ForceHttps;
this.ForceWww = ForceWww;
}
public override void OnActionExecuting(
ActionExecutingContext Context) {
HttpRequestBase Request = Context.HttpContext.Request;
HttpResponseBase Response = Context.HttpContext.Response;
if (!Request.IsLocal) {
Uri Uri;
if (!Request.IsSecureConnection && ForceHttps) {
if (ForceWww) {
Uri = new Uri(Uri.UriSchemeHttps + "://www." + Request.Url.Host.Replace("www.", string.Empty) + "/" + Request.Url.AbsolutePath);
} else {
Uri = new Uri(Uri.UriSchemeHttps + "://" + Request.Url.Host.Replace("www.", string.Empty) + "/" + Request.Url.AbsolutePath);
};
} else if (!ForceHttps) {
if (ForceWww) {
Uri = new Uri(Uri.UriSchemeHttp + "://www." + Request.Url.Host.Replace("www.", string.Empty) + "/" + Request.Url.AbsolutePath);
} else {
Uri = Request.Url;
};
} else {
Uri = Request.Url;
};
Response.RedirectPermanent(Uri.AbsoluteUri, true);
};
}
}
Thanks in advance!