簡體   English   中英

Asp.Net MVC 5將Windows身份驗證與角色提供程序混合在一起

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

我正在嘗試將Windows身份驗證與我自己的角色提供程序混合使用-但似乎無法識別“ IsUserInRole(“ ....”,“ ...”)“

我在“模型”->“安全”文件夾中添加了一個名為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中:

<roleManager cacheRolesInCookie="true" defaultProvider="MTRoleProvider" enabled="true">
  <providers>
    <clear />
    <add name="MTRoleProvider" type="wb.Models.Security.MTRoleProvider" />
  </providers>
</roleManager>

我還補充說:

<authentication mode="Windows" />

然后在我的_layout.cshtml文件中,我嘗試像這樣使用它:

 @if(IsUserInRole(User.Identity.Name,"Admin"))
   {
      <text>Admin mode</text>
   }

User.Identity.Name應該給我Windows用戶名(確實如此),但是IsUserInRole用紅色下划線標出。

在此處輸入圖片說明

如何使系統識別我的新提供者?

謝謝,

標記

使用擴展方法:

 public static bool IsUserInRole(this HtmlHelper helper, string username, string roleName)
    {
       // your code
    }

然后在您看來:

@if(Html.IsUserInRole(userName, Role))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM