我正在使用MVC应用程序和Windows身份验证。 我已经实现了一个自定义角色提供程序,它将返回一个现在从我的数据库中提取的角色数组。
自定义角色提供程序(普通)
public class CustomRoleProvider : RoleProvider
{
...other methods removed...
//Custom Override
public override string[] GetRolesForUser(string username)
{
//Get custom roles from username
using (MyDBEntities db = new MyDBEntities ())
{
var roles = (from p in db.MyProcedure(username)
select p.UserRole).ToArray();
if (roles != null)
{
return roles;
}
else
{
return new string[] { };
}
}
}
}
接下来我要做的是对要返回的用户名进行一些清理。现在我在GetRolesForUser方法中这样做。 我做的第一件事是从域中删除“公司//”,然后我删除使用的某个前缀,然后我通过我们拥有的测试程序运行用户名,如果应用程序是,则将返回模拟的用户名正在接受测试
不要担心所有这些的具体细节。我想要做的就是将清理代码移动到GetUser
方法中的自定义成员资格提供程序,并返回我想要的用户名。我该如何实现呢?
自定义角色提供程序(带有额外代码)
public class CustomRoleProvider : RoleProvider
{
...other methods removed...
//Custom Override
public override string[] GetRolesForUser(string username)
{
//Strip off the domain and lower text
username = username.ToString().ToLower().Split('\\')[1];
//remove company prefix
if (username.Contains("somePrefix-"))
{
username = username.Substring(username.IndexOf("somePrefix-") + 11);
}
//Return impersonated username if being tested
MyRepository myRepository = new MyRepository();
username = myRepository.GetUserName(username);
//I want to move out all of that code from above
//Get custom roles from username
using (MyDBEntities db = new MyDBEntities ())
{
var roles = (from p in db.MyProcedure(username)
select p.UserRole).ToArray();
if (roles != null)
{
return roles;
}
else
{
return new string[] { };
}
}
}
}
自定义成员资格提供程序
我想在这里移动清理代码,所以在登录后,用户名会按照我想要的方式返回。
public class CustomMembershipProvider : MembershipProvider
{
...other methods removed...
public override MembershipUser GetUser(string username, bool userIsOnline)
{
//I'd like to move my custom code here
//Strip off the domain and lower text
username = username.ToString().ToLower().Split('\\')[1];
//remove company prefix
if (username.Contains("somePrefix-"))
{
username = username.Substring(username.IndexOf("somePrefix-") + 11);
}
//Return impersonated username if being tested
MyRepository myRepository = new MyRepository();
username = myRepository.GetUserName(username);
//So now that's I've formatted the username as I want it,
//how can I return that as part of the MembershipUser return type?
}