2

ASP.Net MVC3Webアプリケーションを開発しています。WebサイトをSSL証明書で保護する必要がありますが、これは、アプリケーションがテストサーバーではなく、ライブサーバー上にある場合にのみ使用します。

したがって、WebConfigでAppSettingを次のように設定します。

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

次に、アカウントコントローラーでこの値(TrueまたはFalse)を取得し、その値を使用して、LogOnアクションに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 に答える