2

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

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

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

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

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

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

但是我知道我不能把我的 IF 语句放在现在的位置,但是,希望你能明白我想要实现的目标。

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

谢谢。

4

1 回答 1

1

子类化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);
  }
}

现在您只需像以前一样装饰您的控制器/动作 - 但使用您的新属性:

[RequireHttpsIfEnabled]
public class AccountController : Controller 
{
  //....
}
于 2012-10-10T09:17:18.120 回答