我在.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类private _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对象,因此我们需要在一个IDisposable对象中包装CookieAuthenticationOptions:
public class MyCookieAuthOptions : IDisposable { public MyCookieAuthOptions(CookieAuthenticationOptions cookieOptions) { Options = cookieOptions; } public CookieAuthenticationOptions Options { get; } public void Dispose() { } }