Ashutosh
Ashutosh

Reputation: 201

how to write HTTPS route in mvc 4

I have written the Route in RouteConfig.cs in MVC4. It's working fine with HTTP; i.e:

routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Default", id = UrlParameter.Optional }
);

How can I create HTTPS Route so that some pages can open on HTTPS and some pages on HTTP?

Upvotes: 3

Views: 1625

Answers (2)

haim770
haim770

Reputation: 49095

As @SLaks suggested, you could decorate your Action with the [RequireHttps] attribute.

However, if you don't want to force Https on your Action but only require that the Route will match Https requests only, try to add a RouteConstraint as follows:

public class RequireHttpsConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return httpContext.Request.IsSecureConnection;
    }
}

Then:

routes.MapRoute("SecuredPlaceOrder",
        "/PlaceOrderSecured",
        new { controller = "Orders", action = "PlaceOrder" },
        new { requireSSL = new RequireHttpsConstraint() }
    );

Upvotes: 2

SLaks
SLaks

Reputation: 887355

MVC routes only match the path portion of the URL.
They are completely independent of host or protocol.

If you want to restrict some URLs to HTTPS only, add the [RequireHttps] attribute to the controller or action.

Upvotes: 1

Related Questions