ASP.NET MVC RequireHttps

时间:2009-10-15 18:59:21

标签: asp.net-mvc ssl asp.net-mvc-2 https asp.net-mvc-futures

如何使用ASP.NET MVC 2 Preview 2 Futures RequireHttps属性?

我想阻止将不安全的HTTP请求发送到操作方法。我想自动重定向到HTTPS。

MSDN:

如何使用此功能?

2 个答案:

答案 0 :(得分:15)

我认为你需要为此推出自己的ActionFilterAttribute

public class RedirectHttps : ActionFilterAttribute {
   public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (!filterContext.HttpContext.Request.IsSecureConnection) {
            filterContext.Result = 
                new RedirectResult(filterContext.HttpContext.Request.Url.
                    ToString().Replace("http:", "https:"));
            filterContext.Result.ExecuteResult(filterContext);
        }
        base.OnActionExecuting(filterContext);
    }
}

然后在你的控制器中:

public class HomeController : Controller {

    [RedirectHttps]
    public ActionResult SecuredAction() {
        return View();
    }
}

您可能也想阅读this

答案 1 :(得分:11)

我的猜测:

[RequireHttps] //apply to all actions in controller
public class SomeController 
{
  //... or ...
  [RequireHttps] //apply to this action only
  public ActionResult SomeAction()
  {
  }

}