Asp.net-Mvc-4

在 Startup.Auth.cs 之外訪問配置的 CookieAuthenticationOptions.LoginPath

  • May 8, 2017

我在 .NET MVC 4.5 設置中使用帶有 OWIN 的 cookie 身份驗證。我在 Startup.Auth.cs (下面的程式碼)中設置了 cookie 身份驗證配置,並且我想訪問我在控制器中的 CookieAuthenticationOptions 中設置的 LoginPath ,這樣如果無論出於何種原因,我的 LoginPath 發生更改,我只需要更改它在一個地方。所以只是尋找類似的東西

context.GetCookieAuthenticationOptions().LoginPath

有沒有辦法在 Startup.Auth.cs 之外訪問 CookieAuthenticationOptions,或者我在這裡唯一的選擇是在 Web.config 中添加 appSetting 然後使用它?

Startup.Auth.cs 程式碼,我想在這個文件之外訪問 LoginPath。

       app.UseCookieAuthentication(new CookieAuthenticationOptions
       {
           AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
           LoginPath = new PathString("Login"),
           SlidingExpiration = true,
           ExpireTimeSpan = _expirationTimeSpan,
           Provider = new CookieAuthenticationProvider
           {
               // Enables the application to validate the security stamp when the user logs in.
               // This is a security feature which is used when you change a password or add an external login to your account.  
               OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                   validateInterval: TimeSpan.FromMinutes(30),
                   regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
           },

       });

沒有直接的方法可以做到這一點。如果仔細觀察,cookie 選項對象儲存在AppBuilder類私有_middleware集合中。無法訪問此屬性(反射除外)。

但是,您可以將 cookieOptions 對象儲存在 Owin 上下文中:

var cookieOptions = new CookieAuthenticationOptions
{
   // ...
   LoginPath = new PathString("/Account/Login"),
   // ...
};

app.UseCookieAuthentication(cookieOptions);
app.CreatePerOwinContext(() => new MyCookieAuthOptions(cookieOptions));

在控制器中,您可以像這樣訪問它:

var cookieOptions = HttpContext.GetOwinContext().Get<MyCookieAuthOptions>().Options;

Owin 上下文只支持IDisposable對象,因此我們需要包裝CookieAuthenticationOptions一個IDisposable對象:

public class MyCookieAuthOptions : IDisposable
{
   public MyCookieAuthOptions(CookieAuthenticationOptions cookieOptions)
   {
       Options = cookieOptions;
   }

   public CookieAuthenticationOptions Options { get; }

   public void Dispose()
   {

   }
}

引用自:https://stackoverflow.com/questions/27973792