首页 > 解决方案 > 如何在asp net mvc中将数据字符串更改为getrolesforuser的int?

问题描述

我想将GetRolesForUserASP .net MVC 授权字符串更改为 int。我想通过用户类型 id 获得价值。

这是因为我有多个表。所以我想通过用户类型 id 来检索值。有什么方法可以更改为 int 进行身份验证?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using mylatestproject.Models;

namespace mylatestproject.MyRoleProvider
{
    public class SiteRole : RoleProvider
    {
        public override string ApplicationName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        { throw new NotImplementedException(); }

      public override string[] GetRolesForUser(string username)
        {
            attendanceselangorEntities db = new attendanceselangorEntities();
            string data = db.tblusers.Where(x => x.userNm == username).FirstOrDefault().userNm;
            string[] result = { data };
            return result;
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }
}

此源代码没有错误,但我想将其更改为 int。

标签: asp.net-mvcasp.net-mvc-5

解决方案


创建自定义角色提供者有两个主要原因:

  • 您需要将角色信息存储在 .NET Framework 中包含的角色提供程序不支持的数据源中,例如 FoxPro 数据库、Oracle 数据库或其他数据源。

  • 您需要使用与 .NET Framework 附带的提供程序所使用的数据库架构不同的数据库架构来管理角色信息。一个常见的例子是公司或网站的 SQL Server 数据库中已经存在的角色数据。

在您的情况下,似乎自定义 Authorize 过滤器可以形成更好的解决方案。一些好的线程:

如果必须使用自定义角色提供程序,请更改您的观点并将 userID 作为字符串传递并管理内部逻辑GetRolesForUser以将 ID 转换回int并从多个表中返回关联用户角色。


请发表评论以获得更多说明。


推荐阅读