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

EJa*_*Jay 10 cookies asp.net-mvc-4 owin

我在.NET MVC 4.5设置中使用OWIN进行cookie身份验证.我在Startup.Auth.cs(下面的代码)中设置了cookie身份验证配置,我想访问我在控制器中的CookieAuthenticationOptions中设置的LoginPath,这样如果由于某种原因,我的LoginPath发生了变化,我只需要更改它在一个地方.所以只是寻找类似的东西

context.GetCookieAuthenticationOptions().LoginPath
Run Code Online (Sandbox Code Playgroud) 有没有办法访问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))
            },

        });
Run Code Online (Sandbox Code Playgroud)

Dáv*_*nár 5

没有直接的方法可以做到这一点。如果仔细观察,cookie 选项对象存储在AppBuilder类私有_middleware集合中。无法访问此属性(反射除外)。

但是,您可以将 cookieOptions 对象存储在 Owin 上下文中:

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

app.UseCookieAuthentication(cookieOptions);
app.CreatePerOwinContext(() => new MyCookieAuthOptions(cookieOptions));
Run Code Online (Sandbox Code Playgroud)

在控制器中,您可以像这样访问它:

var cookieOptions = HttpContext.GetOwinContext().Get<MyCookieAuthOptions>().Options;
Run Code Online (Sandbox Code Playgroud)

Owin上下文仅支持IDisposable对象,因此我们需要包装CookieAuthenticationOptions在一个IDisposable对象中:

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

    public CookieAuthenticationOptions Options { get; }

    public void Dispose()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)