Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 776
Ashutosh Avatar asked Feb 04 '26 09:02

Ashutosh


2 Answers

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() }
    );
like image 196
haim770 Avatar answered Feb 12 '26 08:02

haim770


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.

like image 20
SLaks Avatar answered Feb 12 '26 08:02

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!