ASP.Net Core应用程序中的成员资格提供程序

时间:2018-07-31 15:09:38

标签: c# asp.net-core asp.net-membership

我正在强制将成员资格提供程序添加到ASP.Net Core应用程序的配置中的问题。我必须添加它,因为它引用了包含旧代码的旧项目,并引用了System.Web.ApplicationServices的程序集。在此程序集中,流程转到第几行,该行将检查提供程序的名称是否不为空。

if ( providerName == null || SystemWebProxy.Membership.Providers[providerName] == null )
        {
            throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ApplicationServicesStrings.Membership_provider_name_invalid), "providerName" );
        }

但是无论如何,我在appsettings.json中添加了必要的实现:

"Membership": {
"DefaultProvider": "blahblah",
"Providers": {
  "Add": {
    ...
    "Name": "blahblah"
    ...
  }
}}

在启动类中,我通过以下方式配置sqlMembershipProvider

services.Configure<System.Web.Security.SqlMembershipProvider>(Configuration.GetSection("Membership"));

有人可以告诉我,为什么我没有将提供程序实现到配置中吗?也许我走错路了?

1 个答案:

答案 0 :(得分:0)

您可以尝试类似的操作:

首先,定义用于处理appsettings.json的类

public class MembershipSettings{
    public string DefaultProvider { get; set; }
    public Provider Provider { get; set; }
}

public class Provider
{
    public string Name { get; set; }
    public string ConnectionStringName { get; set; } //not sure if it works
    public string ApplicationName { get; set; }
    //etc
}

然后从SqlMembershipProvider继承

internal class CustomeSqlMembershipProvider : SqlMembershipProvider
{
    public CustomeSqlMembershipProvider(IOptions<MembershipSettings> settings)
    {
        InitializeProvider(settings.Value);
    }

    protected virtual void InitializeProvider(MembershipSettings settings)
    {
        base.Initialize(settings.Provider.Name, PrepareSettings(settings.Provider));
    }

    private NameValueCollection PrepareSettings(Provider provider) => new NameValueCollection
    {
        //you can use reflection to do that as well

        { nameof(provider.ApplicationName), provider.ApplicationName},
        {nameof(provider.ConnectionStringName), provider.ConnectionStringName}

        //...
        //etc
    };
}

然后在Startup.cs中添加以下行:

services.Configure<MembershipSettings>(Configuration.GetSection("Membership"));
services.AddScoped<SqlMembershipProvider, CustomSqlMembershipProvider>();

最后但并非最不重要的一点是,稍微修改一下appsettings.json(您可以调整MembershiSettings类和CustomSqlMembershiProvider来处理和初始化提供者列表)

"Membership": {
    "DefaultProvider": "blahblah",
    "Provider": {
        ...
        "Name": "blahblah"
        ...
    }
}

请注意,我对SqlMembershipProvider不太熟悉,因此可能存在一些缺陷。我认为您应该编写自己的MembershipProvider,但如果不能(由于遗留代码),则可以执行上述操作