Sunday, February 22, 2009

RequireSSL Attribute For ASP.NET

Here is a quick Custom Attribute in order to Define if a Page must be in HTTP SSL Mode and switch it to SSL if not.

[AttributeUsage(AttributeTargets.Class)]
public class RequireSSLAttribute : Attribute
{
public static void Validate(IHttpHandler handler)
{
Type type = handler.GetType();
Object[] objs = type.GetCustomAttributes(typeof(RequireSSLAttribute), true);
if (objs != null && objs.Count() > 0)
{
SwitchToSsl();
}
}
private static void SwitchToSsl()
{
#if DEBUG
return;
#endif
String baseUrl = HttpContext.Current.Request.Url.OriginalString;
Uri uri = new Uri(baseUrl);
String url = baseUrl.Replace(uri.Scheme, Uri.UriSchemeHttps);
HttpContext.Current.Response.Redirect(url, true);
}
}

A Sample Page Implementation

In order to make it working, you just need to call RequireSSLAttribute Validate Method. On Page Constructor might be fine :)

[RequireSSL]
public partial class _Default : Page
{
public _Default()
{
RequireSSLAttribute.Validate(this);
}

protected void Page_Load(object sender, EventArgs e)
{
}
}
Source : http://blog.sb2.fr/post/2008/12/20/RequireSSL-Attribute-For-ASPNET.aspx

No comments:

Post a Comment