您可以制作一个动作过滤器来检查 https。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class HttpsOnlyAttribute : ActionFilterAttribute
{
/// <summary>
/// Called by the MVC framework before the action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsSecureConnection)
{
throw new HttpException(404, "HTTP/1.1 404 Not Found");
}
}
}
只需将属性放在您只想成为 https 的控制器的顶部
[HttpsOnly]
public class SecureController : Controller
{
// your actions here
}
您甚至可以只针对操作
public class SampleController : Controller
{
[HttpsOnly]
public ActionResult SecureAction()
{
return View();
}
}