的真正用例是仅在请求身份验证时RequireHttpsAttribute
强制执行该方案。https://
并非在所有情况下。RequireHttpsAttribute只实现了IAuthenticationFilter接口的OnAuthentication方法。
由于仅在 InvokeAuthenticationFilters 方法中调用OnAuthentication方法,因此我不会使用该RequireHttpsAttribute
属性。
为了正确执行https://
某些控制器或操作,我将创建自己的属性,基于ActionFilterAttribute
:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class EnforceHttpsActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (new[] { "GET", "HEAD" }.Any(verb => String.Equals(filterContext.HttpContext.Request.HttpMethod, verb, StringComparison.OrdinalIgnoreCase))) ;
{
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url);
}
}
}
要对整个站点强制执行,您可以从我用于示例应用程序实例的web.config 标记https://
中获得灵感。*.azurewebsites.net
<system.webServer>
<rewrite>
<rules>
<rule name="HTTPS Redirect in Azure">
<match url="(.+)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
<add input="{HTTP_HOST}" pattern="^(.+)\.azurewebsites.net(.*)$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="SeeOther" />
</rule>
</rules>
</rewrite>
</system.webServer>