我有一个自定义的 RequireHttps 操作过滤器。我登录并且我的网站是 https,但是当您在登录时输入 http 页面时,操作过滤器永远不会被击中。我知道这一点,因为我已经登录并且我没有看到它被记录了。我希望它得到它的原因是测试用户是否经过身份验证并执行 301 重定向到 SSL 中的同一页面,但它永远不会被击中。
全球.asax
kernel.BindFilter<UseHttpsFilter>(FilterScope.Action, 0)
.WhenActionMethodHas<UseHttpsAttribute>()
.WithConstructorArgumentFromActionAttribute<UseHttpsAttribute>("requireSecure", q => q.RequireSecure);
kernel.BindFilter<UseHttpsFilter>(FilterScope.Controller, 0)
.WhenActionMethodHas<UseHttpsAttribute>()
.WithConstructorArgumentFromControllerAttribute<UseHttpsAttribute>("requireSecure", q => q.RequireSecure);
使用HttpsAttribute.cs
namespace Site.Web.Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class UseHttpsAttribute : FilterAttribute
{
public bool RequireSecure { get; set; }
public UseHttpsAttribute(bool requireSecure)
{
RequireSecure = requireSecure;
}
}
public class UseHttpsFilter : ActionFilterAttribute
{
protected static readonly NLogLogger Logger = new NLogLogger();
public bool RequireSecure = false;
public UseHttpsFilter(bool requireSecure)
{
Logger.Debug("Use Https Constructor: " + requireSecure);
RequireSecure = requireSecure;
}
protected virtual void HandleNonHttpRequest(ActionExecutingContext filterContext)
{
if (string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url, true);
}
}
protected void HandleNonHttpsRequest(ActionExecutingContext filterContext)
{
if (string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url, true);
}
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Logger.Debug("Use Https Authenticated: " + filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated);
if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated || HttpContext.Current.Session[Config.ViewData.MemberSession] != null)
{
RequireSecure = true;
}
Logger.Debug("Use Https Local: " + filterContext.RequestContext.HttpContext.Request.IsLocal);
if (filterContext.RequestContext.HttpContext.Request.IsLocal)
RequireSecure = false;
if (RequireSecure)
{
Logger.Debug("Use Https Secure Connection: " + filterContext.HttpContext.Request.IsSecureConnection);
if (!filterContext.HttpContext.Request.IsSecureConnection)
{
HandleNonHttpsRequest(filterContext);
}
}
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
}
}
}