Search code examples
c#asp.net-mvc-2sslrequirehttps

MVC RequireHttps and redirect if not https


I've read thru many of the questions on ASP.NET MVC [RequireHttps] - but can't find the answer to this question:

How do you make the [RequireHttps] attribute switch the url to https if it was not https to start with?

I have this code:

public ActionResult DoSomething()
{
    return View("AnotherAction");
}

[RequireHttps]
public ActionResult AnotherAction()
{
    return View();
}

But I get an error saying: "The requested resource can only be accessed via SSL."

The MVC futures project has a similar attribute [RequireSsl(Redirect = true)]. But that is outdated now ... What is the equivalent in MVC 2?

When someone types in the URL http://example.com/home/dosomething OR the url http://example.com/home/anotheraction, I need them to be automatically redirected to the url https://example.com/home/anotheraction

EDIT this is the sequence of events:

The URL http://example.com/home/dosomething is called from another website. They redirect their users to this url (with a response.redirect or similar).

DoSomething() then tries to return AnotherAction(), but fails with the error message "The requested resource can only be accessed via SSL."


Solution

  • The RequiresHttps attribute does automatically attempt to redirect to https://your-url. I verified this behavior on a site I have that uses that attribute, and also looking at the code in Reflector:

    protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext)
    {
        if (!string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException(MvcResources.RequireHttpsAttribute_MustUseSsl);
        }
        string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
        filterContext.Result = new RedirectResult(url);
    }
    

    Are you sure you have your site set up to accept secure connections? What happens if you try to browse to https://your-url directly?