不使用Web.Config配置表单身份验证

Dwa*_*ang 5 c# asp.net-mvc forms-authentication web-config global-asax

脚本


我已经将我的MVC应用程序配置为以传统方式使用Forms身份验证.

<authentication mode="Forms">
  <forms cookieless="UseCookies" slidingExpiration="true" timeout="1">
  </forms>
</authentication>
Run Code Online (Sandbox Code Playgroud)

但是,我允许客户端选择他的Web应用程序如何进行身份验证(URL令牌/ Cookie),以及他的应用程序会话在到期之前应该持续多长时间(超时)


我有办法通过代码执行此操作吗?我只通过web.config看过这个的实现?

我想从数据库中读取设置并将它们应用于Global.asax - > OnApplicationStart()

小智 3

看看WebActivatorEx。这是一个关于其功能的好博客。要配置 FormsAuthentication,您甚至必须在应用程序启动之前执行配置方法。WebActivatorEx 将为您处理。如果您不想使用第三方包,您可以在 AssemblyInfo.cs 类中指定此[程序集:PreApplicationStartMethod(typeof(AppConfig), "Configure")] 。这是谈论它的另一个参考点。

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(AppConfig), "Configure")]
public static class AppConfig
{
    public static void Configure()
    {
        var settings = new NameValueCollection();
        settings.Add("defaultUrl", "~/Account/Default.aspx");
        settings.Add("loginUrl", "~/Default.aspx");
        settings.Add("timeout", "10");
        FormsAuthentication.EnableFormsAuthentication(settings);
    }
}
Run Code Online (Sandbox Code Playgroud)