此操作过滤器似乎不能始终如一地工作。有时它会关闭SSL,有时则不会。我已将它应用于整个控制器的声明。
public class SSLFilter:ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase req = filterContext.HttpContext.Request;
HttpResponseBase res = filterContext.HttpContext.Response;
if (req.IsSecureConnection)
{
var builder = new UriBuilder(req.Url)
{
Scheme = Uri.UriSchemeHttp,
Port = 80
};
res.Redirect(builder.Uri.ToString());
}
base.OnActionExecuting(filterContext);
}
}
这有点奇怪......为什么它可能偶尔起作用的任何想法?
答案 0 :(得分:0)
您是否尝试使用[RequireHttps]
属性修改控制器/操作?
糟糕,没有注意到你在询问ASP.NET MVC 2.这个属性仅在ASP.NET MVC 3中可用,所以这里是它的源代码(在ASP.NET MVC 3中实现): / p>
using System;
using System.Diagnostics.CodeAnalysis;
using System.Web.Mvc.Resources;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class RequireHttpsAttribute : FilterAttribute, IAuthorizationFilter {
public virtual void OnAuthorization(AuthorizationContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if (!filterContext.HttpContext.Request.IsSecureConnection) {
HandleNonHttpsRequest(filterContext);
}
}
protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext) {
// only redirect for GET requests, otherwise the browser might not propagate the verb and request
// body correctly.
if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {
throw new InvalidOperationException(MvcResources.RequireHttpsAttribute_MustUseSsl);
}
// redirect to HTTPS version of page
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url);
}
}
请注意,如何使用RedirectResult而不是执行任何重定向,这是在ASP.NET MVC中执行重定向的正确方法=>通过返回行动结果:
filterContext.Result = new RedirectResult(url);
不仅如此,这将执行正确的重定向,而且这是如何使操作的执行短路。从语义上讲,您的过滤器实际上应该是IAuthorizationFilter,因为您在此处阻止对某些资源的访问。