角色提供程序上的值不能为null

时间:2016-10-07 18:38:01

标签: c# asp.net-mvc asp.net-mvc-5 roleprovider

我是MVC C#的初学者。现在我正在尝试使用角色提供程序构建自定义身份验证,但是当它检查用户角色时,它会收到“Value not not null”的错误。 这是我的RoleProvider:

public class MyRoleProvider:RoleProvider
{
    private int _cacheTimeoutInMinute = 20;
    LoginGateway gateway=new LoginGateway();


public override string[] GetRolesForUser(string username)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            return null;
        }

        //check cache
        var cacheKey = string.Format("{0}_role", username);
        if (HttpRuntime.Cache[cacheKey] != null)
        {
            return (string[])HttpRuntime.Cache[cacheKey];
        }
        string[] roles

            = gateway.GetUserRole(username).ToArray();
            if (roles.Any())
            {
                HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);

            }

        return roles;
    }
public override bool IsUserInRole(string username, string roleName)
    {
        var userRoles = GetRolesForUser(username);
            return userRoles.Contains(roleName);   

    }

它始终在reurn userRoles.Contains(roleName);上获取错误(值不能为null(userName))行。我使用了调试指针,它显示网关从未被调用。我,e:string[] roles = gateway.GetUserRole(username).ToArray();因此角色始终保持为空。 虽然我不确定网关上的GetUserRole方法是否正确:这是我的网关:

public string[] GetUserRole(string userName)
    {

        string role = null;
        SqlConnection connection = new SqlConnection(connectionString);
        string query = "select r.RoleType from RoleTable r join UserRoleTable ur on ur.RoleId=r.Id join UserTable u on u.UserId=ur.UserId where u.UserName='"+userName+"'";
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            role = reader["RoleType"].ToString();

        }
        string[] roles = {role};
        reader.Close();
        connection.Close();
        return roles;
    }  

我的代码有问题吗?我怎么能解决这个错误?

1 个答案:

答案 0 :(得分:0)

  

如果我删除或注释掉httpContext和所有代码,它都有效   缓存...缓存部分代码有什么问题吗? @win

我不担心会遇到数据库,除非您正在开发速度有问题且每个查询都很重要的企业应用程序。 原始ASP.Net会员提供商根本不使用缓存。

此外,ASP.Net会员提供商是一项非常古老的技术 - 十多年前的。如果要实施企业应用程序,则可能需要考虑使用基于声明的身份验证。

如果您想使用 -

,这是缓存服务
using System;
using System.Collections.Generic;
using System.Runtime.Caching;

public class CacheService 
{
    protected ObjectCache Cache => MemoryCache.Default;

    public T Get<T>(string key)
    {
        return (T) Cache[key];
    }

    public void Set(string key, object data, int cacheTime)
    {
        if (data == null)
            return;

        var policy = new CacheItemPolicy();
        policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
        Cache.Add(new CacheItem(key, data), policy);
    }

    public void Remove(string key)
    {
        Cache.Remove(key);
    }
}