Reputation: 7818
I'm trying to mix Windows authentication, with my own Role Provider - but I can't seem to get it to recognise "IsUserInRole("....","...")"
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;
}
}
}
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>
I also added:
<authentication mode="Windows" />
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 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?
Thank you,
Mark
Upvotes: 1
Views: 2323
Reputation: 1950
Use Extesion Method:
public static bool IsUserInRole(this HtmlHelper helper, string username, string roleName)
{
// your code
}
then in your view:
@if(Html.IsUserInRole(userName, Role))
Upvotes: 1