问题描述
我正在尝试将Windows身份验证与我自己的角色提供程序进行混合,但我似乎无法将其识别为IsUserInRole(....,...)
I'm trying to mix Windows authentication, with my own Role Provider - but I can't seem to get it to recognise "IsUserInRole("....","...")"
我添加了一个新的类到我的Models - > Security文件夹,名为MTRoleProvider:
I added a new class to my Models -> Security folder, named MTRoleProvider:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace wb.Models.Security
{
public class MTRoleProvider : RoleProvider
{
private BoardContext db = new BoardContext();
public override string[] GetRolesForUser(string username)
{
var roleNames = db.UserRole.Where(x => x.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase)).Select(x => x.Role);
if (roleNames.Count() > 0)
return roleNames.ToArray();
else
return new string[] { };
}
public override bool IsUserInRole(string username, string roleName)
{
var user = db.UserRole.Where(x => x.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase) && x.Role.Equals(roleName,StringComparison.CurrentCultureIgnoreCase));
if (user != null)
return true;
else
return false;
}
}
}
在我的web.config - 我添加到system.web:
In my web.config - I added this to system.web:
<roleManager cacheRolesInCookie="true" defaultProvider="MTRoleProvider" enabled="true">
<providers>
<clear />
<add name="MTRoleProvider" type="wb.Models.Security.MTRoleProvider" />
</providers>
</roleManager>
我还添加了:
<authentication mode="Windows" />
然后在我的_layout.cshtml文件中,我尝试使用它:
Then in my _layout.cshtml file, I tried to use it like this:
@if(IsUserInRole(User.Identity.Name,"Admin"))
{
<text>Admin mode</text>
}
User.Identity.Name应该给我的Windows用户名(它所做的)但是 IsUserInRole
在Red中加下划线。
User.Identity.Name should give my Windows username (which it does), but IsUserInRole
is underlined in Red.
如何让系统识别我的新供应商?
How can I get the system to recognise my new provider?
谢谢,
标记
推荐答案
使用Exiterion方法:
Use Extesion Method:
public static bool IsUserInRole(this HtmlHelper helper, string username, string roleName)
{
// your code
}
然后在您的视图中:
@if(Html.IsUserInRole(userName, Role))
这篇关于新新200新200新新200新新200新200新新200新新200新200新新200新新200新新200新新200新新200新新200新新200新新200新新200新新新200新新200新新200的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!