Edit: By Overriding the RoleProvider we were hoping to still use the same method开发者_运维百科s with our new methods. Such as Roles.GetRolesForUser(int).
string[] myRoles3 = ((PortalRoleProvider) (Roles.Provider)).GetRolesForUser(2);
That above code seems a bit excessive ?
I have a class which overrides some members of the RoleProvider and adds new methods. Eg.
public string[] GetRolesForUser(int UserId)
{
IEnumerable<Role> RoleList = _Repo.GetRolesForUser(UserId);
string[] RetVal = new string[] {};
foreach (var curRole in RoleList)
{
RetVal[RetVal.GetUpperBound(0)] = curRole.RoleName;
}
return RetVal;
}
Now when I am in the logic of my code I want to write Roles.GetRolesForUser(2) but when i type this, it does seem to see the extra method that I have added. Here is the class declaration and the webconfig.
namespace PortalMVC.Providers
{
public class PortalRoleProvider : RoleProvider
{
Web.config
<roleManager enabled="true" defaultProvider="PortalRoleProvider">
<providers>
<clear/>
<add name="PortalRoleProvider" type="PortalMVC.Providers.PortalRoleProvider"/>
</providers>
</roleManager>
Any suggestions why this is?
You have to cast your RoleProvider as your actual object type (i.e. PortalRoleProvider) to see the extra functions. This applies to any time you've extended a standard object but are accessing it as it's super class (Master pages, etc.)
string[] myRoles3 = ((PortalRoleProvider) (Roles.Provider)).GetRolesForUser(2);
The above, as you've pointed out in your post, works. If you need to use this a lot in a section of code, you can create a pointer with the proper type then access the methods from there:
PortableRoleProvider TempPointer=(PortableRoleProvider)Roles.Provider;
string[] myRoles3=TempPointer.GetRolesForUser(2);
In the web.config, where you specify the type for the role provider, you might need to add the name of the assembly where the type can be found. Something like this:
<add name="PortalRoleProvider" type="PortalMVC.Providers.PortalRoleProvider, MyAssemblyName" />
精彩评论