The important functionality of any ecommerce system is to transfer the content using SSL when the user enters the user name & password or while accepting the credit card info. Steve Sanderson has blogged about this and unfortunately it didn’t work for me. Also MVC Futures has RequiresSSL extension which transform the content to secure. But in a typical system, we need to redirect back to HTTP as well, i.e if there is a booking flow, after we get the credit card and validating the payment details, the confirmation page might or should be in HTTP.

There are various solution available, i have decided to use the MVC Futures code and slightly modify the same to implement this functionality.

public sealed class SwitchSsl : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!Enable)
            return;

        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }
        if (!filterContext.HttpContext.Request.IsSecureConnection && Mode==Protocol.https)
        {
            if (!this.Redirect)
            {
                throw new HttpException(0x193, "Must use SSL");
            }
            RedirectUrl(Protocol.https, filterContext);
        }
        else if (filterContext.HttpContext.Request.IsSecureConnection && Mode==Protocol.http)
        {
            RedirectUrl(Protocol.http, filterContext);
        }
    }

    public bool Redirect { get; set; }

    public Protocol Mode { get; set; }

    public bool Enable
    {
        get {
            return Convert.ToBoolean(ConfigurationManager.AppSettings.Get("EnableSsl"));
        }
    }

    private void RedirectUrl(Protocol scheme, AuthorizationContext filterContext)
    {
        UriBuilder builder2 = new UriBuilder();
        builder2.Scheme = scheme.ToString();
        builder2.Host = filterContext.HttpContext.Request.Url.Host;
        builder2.Path = filterContext.HttpContext.Request.RawUrl;
        UriBuilder builder = builder2;
        filterContext.Result = new RedirectResult(builder.ToString());
    }

    public enum Protocol
    {
        http,
        https
    }

}

Enable property is an optional configuration in the web.config, so that we can enable this only in the production environment. And in the controller action,we can call like below.

[SwitchSsl(Redirect = true, Mode=SwitchSsl.Protocol.https)]
public ActionResult Reserve()

Happy Coding!


 
Categories: ASP.NET MVC