asp.net-mvc-4 – 在Startup.Auth.cs之外配置的CookieAuthenticationOptions.LoginPath访问

我在.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()
    {

    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....