ASP.NET MVC RequireHttps

旧巷老猫 提交于 2019-11-26 21:33:30

问题


How do I use the ASP.NET MVC 2 Preview 2 Futures RequireHttps attribute?

I want to prevent unsecured HTTP requests from being sent to an action method. I want to automatically redirect to HTTPS.

MSDN:

  • RequireHttpsAttribute
  • RequireHttpsAttribute Members
  • RequireHttpsAttribute.HandleNonHttpsRequest Method

How do I use this feature?


回答1:


My guess:

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

}



回答2:


I think you're going to need to roll your own ActionFilterAttribute for that.

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);
    }
}

Then in your controller :

public class HomeController : Controller {

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

You might want to read this as well.



来源:https://stackoverflow.com/questions/1574347/asp-net-mvc-requirehttps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!