0

I want to use https for a single page instead of whole website. My application is in MVC3. I have used below code to accomplish this.

[RequireHttps]
public ViewResult YourAction()

But after routing to my particular action, the whole website runs under https. I want to use https for a single page not for whole website.

Jitendra Pancholi
  • 7,897
  • 12
  • 51
  • 84
  • 2
    http://stackoverflow.com/questions/7846833/why-once-ssl-is-enabled-with-requirehttps-at-action-level-it-remains-enabled – Chuck Norris Jun 22 '12 at 06:35
  • I didn't get proper answer, In the example taken in the link, i have to write that attribute on each action if i want/ or do not want to use https. Can anyone provide a better approach. – Jitendra Pancholi Jun 22 '12 at 07:19
  • Why not just let it run under SSL? Like the one answer said in the thread Chuck Norris metnioned, usually its really wrong to switch back to unencrypted after doing something in SSL. – Tim Jun 22 '12 at 19:06

1 Answers1

0

I have done it using below code.

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
                filters.Add(new LimitHttpsAttribute());
            }

 public class LimitHttpsAttribute : IAuthorizationFilter
    {
        private static Type ssl = typeof(RequireHttpsAttribute);

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
            {
                if (!filterContext.HttpContext.Request.IsSecureConnection ||
                    filterContext.HttpContext.Request.IsAuthenticated)
                {
                    return;
                }
                if (!RequiresSSL(filterContext))
                {
                    filterContext.Result = Unencrypted(filterContext.HttpContext.Request);
                }
            }
        }

        private bool RequiresSSL(AuthorizationContext filterContext)
        {
            return filterContext.ActionDescriptor != null ?
                filterContext.ActionDescriptor.GetCustomAttributes(ssl, true).Length > 0
                : false;
        }
}
Jitendra Pancholi
  • 7,897
  • 12
  • 51
  • 84