3

好的,我已经创建了自定义角色提供程序并将其添加到 web.config。这是我的角色提供者代码的一部分:

public class MyCustomRoleProvider : RoleProvider
{
    public override bool IsUserInRole(string username, string roleName)
    {
        return true;
    }

    public string MyCustomFunction()
    {
        return "its my custom string";
    }
}

当我需要在我的应用程序中使用角色提供者时,我会这样称呼它:

var truth = Roles.IsUserInRole("myUsername", "myFakeRole");

好的,太好了!它调用我的自定义代码(我可以从调试中看出)并且每次都返回 true。为什么我不能对我的自定义角色提供程序进行以下调用?

var no_compile = Roles.MyCustomFunction();

如何使我的自定义角色提供程序的所有公共成员都可以访问?

4

2 回答 2

2

I do not really know what is the problem, but you should be able to do

var no_compile = _Roles.MyCustomFunction();

If _Roles defines a new MyCustomRoleProvider since the function is public

Example

MyCustomRoleProvider _Roles = new MyCustomRoleProvider();
var no_compile = _Roles.MyCustomFunction();

Notice that: You can not call MyCustomRoleProvider.MyCustomFunction() directly because it is not a public static string.


Notice that: System.Web.Security.Roles is a class which contains the same function name of your class IsUserInRole(string username, string roleName) but the function is not the same in both classes. So, you can not access Roles.MyCustomFunction() because the class System.Web.Security.Roles does not contain a definition for MyCustomFunction() and that's because you did not define a new function in the class

  • MyCustomRoleProvider and System.Web.Security.Roles are TWO different classes which have different functions

System.Web.Security.Roles contains a definition for IsUserInRole(string username, string roleName) (+1 overload)

Notice that: You can not modify or add functions to System.Web.Security.Roles as it is write-protected

System.Web.Security.Roles is write protected

Thanks,
I hope you find this helpful :)

于 2012-10-31T20:27:05.693 回答
2

原因是这Roles.IsUserInRole是一个静态方法,它有一个实现来选择当前RoleProvider并执行它的IsUserInRole 实例方法。内部使用的类型不是MyCustomRoleProvider类型,而是RoleProvider. 这实际上是这个问题:

public class BaseClass
{
    public virtual void Foo() { }
}

public class DerivedClass
{
    public virtual void Foo() { }

    public void MoreFoo() { }
}

BaseClass instance = new DerivedClass();
instance.MoreFoo(); // Doesn't compile

该类,即使它是派生版本,由于它被用作基类型,不知道您在自定义提供程序中的实现。

为了使其可访问,您可以创建自己的静态实现,在内部可以执行您希望它执行的所有调用:

public static class Roles
{
    protected static Lazy<MyCustomProvider> _provider = new Lazy<MyCustomProvider>(() => System.Web.Security.Roles.Provider);

    public static MyCustomProvider Provider { get { return _provider.Value; } }

    public static IsUserInRole(string userName, string roleName)
    {
        return _provider.Value.IsUserInRole(userName, roleName);
    }

    public static MyCustomFunction()
    {
        return _provider.Value.MyCustomFunction();
    }
}
于 2012-10-31T21:23:08.503 回答