在 Startup.Auth.cs 之外配置的访问权限 CookieAuthenticationOptions.LoginPath

Access configured CookieAuthenticationOptions.LoginPath outside of Startup.Auth.cs

我在 .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 class 私有 _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()
    {

    }
}