简体   繁体   中英

Asp.Net MVC 5 mixing Windows authentication with a role provider

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM