Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't [RequireHttps] in MVC do a 301 permanent redirect? Why does it do a 302 (bad for SEO?)

I noticed on fiddler that [RequireHttps] does status code 302 redirects instead of 301. I'm not sure how this makes sense...

If you are saying that a controller [RequireHttps], then you never-ever want people to go visit the Http version of that page. So why isn't a permanent redirect... telling the search engines "please update your links permanantly to the https version of this page".

If this makes sense, and i'm right, is there a way to change it to 301 redirect?

like image 900
Ralph N Avatar asked Mar 08 '12 20:03

Ralph N


2 Answers

For .Net Core 3 we use custom filter as we do need exclude specific URLs

public sealed class PortalCustomRequireHttpsAttribute: RequireHttpsAttribute
{
    ....
    public override void OnAuthorization( AuthorizationFilterContext FilterContext )
    {
        // Custom logic to detect if HTTPs is required
        if( requiresHttps )
        {
            Permanent = true;
            base.OnAuthorization( FilterContext );
        }
    }
}
like image 135
Maxim Avatar answered Oct 08 '22 00:10

Maxim


Dulan's answer is close, but it does not work, at least with our MVC 4+ solution. But after some trial and error, we did get ours working with 301's instead of 302's. Here is the new class:

public class CustomRequireHttpsAttribute : RequireHttpsAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        #if !DEBUG
        base.OnAuthorization(filterContext);

        if (!filterContext.HttpContext.Request.IsSecureConnection)
        {
            string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
            filterContext.Result = new RedirectResult(url, true);
        }
        #endif
    }
}

The reason Dulan's answer didn't work seems to be because the Permanent property of the filterContext.Result is readonly and can only be set when the RedirectResult() is called, and the problem is that RedirectResult() is called in the base.OnAuthorization() method. So just call the base method, then override the filterContext.Result below with the second parameter of true to make the result Permanent. After doing this, we began to see 301 codes in Fiddler2.

like image 44
John Washam Avatar answered Oct 08 '22 00:10

John Washam