我正在开发 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
{
//....
}
我是一名优秀的程序员,十分优秀!