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?
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 );
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With