asp.net-mvc-3 - Controller 操作之外的 ASP.Net MVC 3 IF 语句

标签 asp.net-mvc-3 ssl

我正在开发 ASP.Net MVC 3 Web 应用程序。我需要使用 SSL 证书保护我的网站,但是,我只希望在应用程序在我的实时服务器上而不是在我的测试服务器上时使用它。

因此,我像这样在我的 Web Config 中设置了一个 AppSetting

<appSettings>
    <add key="SSL" value="false" />
</appSettings>

然后在我的帐户 Controller 中我得到这个值(True 或 False)并使用该值决定是否在我的登录操作上设置 RequiresHttps 属性。我想做这样的事情

public class AccountController : Controller
{
        public string SSL = System.Configuration.ConfigurationManager.AppSettings["SSL"];

        if (SSL.Equals("true"))
        {
            [RequireHttps]
        }
        public ActionResult LogOn()
        {
            return View();
        }
}

但我知道我不能将 IF 语句放在当前位置,但是,希望您了解我要实现的目标。

有人对我如何实现我的想法有任何建议吗?

谢谢。

最佳答案

RequireHttpAttribute 的子类(请注意,此代码已从我原来的答案更改而来 - 这个新版本会更高效):

public class RequireHttpsIfEnabledAttribute : RequireHttpsAttribute
{
  //this setting can't be changed without a recycle, so get it once and cache it.
  private static readonly Lazy<bool> HttpsRequired = new Lazy<bool>(() => {
    //if the AppSettings["SSL"] returns null you raise an exception if you do a
    //.Equals on it - so do it on the constant instead.  And make sure it's case
    //insensitive!
    return "true".Equals(System.Configuration.ConfigurationManager.AppSettings["SSL"],
      StringComparison.OrdinalIgnoreCase);
  });
  public override void OnAuthorization(AuthorizationContext filterContext)
  {
    //calling the base will fire the HTTPS check.  Not calling it will allow
    //non-SSL requests through
    if (HttpsRequired.Value)  
      base.OnAuthorization(filterContext);
  }
}

现在您只需像以前一样装饰您的 Controller /操作 - 但使用您的新属性:

[RequireHttpsIfEnabled]
public class AccountController : Controller 
{
  //....
}

关于asp.net-mvc-3 - Controller 操作之外的 ASP.Net MVC 3 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12815825/

相关文章:

java - 为什么 HttpsURLConnection.getServer Certificates() 在 Java 6 和 Java 7 中返回不同的结果?

authentication - 如何防止客户端检索我的服务器证书

c# - return View(model) 和 return RedirectToAction ("ViewName",model) 有什么区别

asp.net-mvc - 不同形式的预编译会影响性能吗?

PHP: PDO(MySQL) SSL 连接

ssl - 可以针对浏览器(作为客户端)测试 2 向 SSL 吗?

java - 我可以使用 keytool 创建没有密码的 Java 信任库吗?

vb.net - ASP.NET MVC3 - VB 中的 If 语句

asp.net-mvc-3 - 如何在 ASP.NET MVC 3 中使用 System.Web.UI.WebControls.Button

jquery - asp.net mvc3 文本区域的水印