LLM LLM - 1 year ago 120
HTTP Question

How to redirect HTTP to HTTPS of MVC application (IIS7.5)

I need to redirect my Http site to HTTPS, have added below rule but I am getting 403 Error when tried using http://www.example.com, it working fine when I type https://www.example.com in browser.

<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
<action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />

Please let me know if any other issue with it.


Answer Source

You can do it in code:


protected void Application_BeginRequest(){
    if (!Context.Request.IsSecureConnection)
        Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));

Or You could add the same code to an action filter:

public class SSLFilter : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext){
        if (!filterContext.HttpContext.Request.IsSecureConnection){
            var url = filterContext.HttpContext.Request.Url.ToString().Replace("http:", "https:");
            filterContext.Result = new RedirectResult(url);