web 2.0

RequireSSL Attribute For ASP.NET

Hi,

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.

The RequireSSLAttribute Implementation

[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)
    {
    }
}

 

Hope this Help’s!



Views(1027)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | ASP.NET

Comments

Add comment


 

biuquote
Loading



Technorati Profile