ASP.NET MVC自定义RoleProvider无法从数据库中检索用户名的角色

时间:2016-04-22 13:57:35

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

我似乎找不到上述问题的正确解决方案。我一直在System.NullReferenceException: Object reference not set to an instance of an object.

我遵循了本指南http://techbrij.com/custom-roleprovider-authorization-asp-net-mvc

错误消息来自我在线var user = _VisitorService.GetVisitors().FirstOrDefault(u => u.Username == username);的GetRolesForUser(字符串用户名)的自定义角色提供者

VisitorService在Controller中工作,但不在RoleProvider中工作。

下面是代码,请根据需要提供建议。提前谢谢你。

自定义RoleProvider

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TamilLeague.Service;

namespace TamilLeague.WebUI
{
    public class myRoleProvider : System.Web.Security.RoleProvider
    {
        private readonly IVisitorService _VisitorService;
        public myRoleProvider(IVisitorService visitorservice)
        {
            _VisitorService = visitorservice;
        }
        public myRoleProvider() { }

        public override string[] GetRolesForUser(string username)
        {            
            var user = _VisitorService.GetVisitors().FirstOrDefault(u => u.Username == username);
            if (user == null)
                return null;
            else
            {
                string role = user.Role.Title;
                string[] rol = { role };
                return rol;
            }
        }
}

我的控制器

[AllowAnonymous]
        [HttpPost]
        public ActionResult Login(UserLoginVM thisUser, string returnUrl)
        {
            var visitor = _VisitorService.GetVisitors().FirstOrDefault(v => v.Username.ToLower() == thisUser.Username.ToLower());

            if (visitor == null)
            {
                ModelState.AddModelError("Username", "Username not found in system. Please register or change the username.");
            }
            if(!visitor.checkPassword(thisUser.HashedPassword))
            {
                ModelState.AddModelError("Username", "Username or password is incorrect.");
            }

            if (visitor.IsFreezed == true)
            {
                ModelState.AddModelError("Username", "Account is freezed. Contact the administrator please.");
            }

            if (visitor.IsConfirmed == false)
            {
                ModelState.AddModelError("Username", "Account is not activated. Contact the administrator please or log into your email to activate your account.");
            }

            if (ModelState.IsValid)
            {
                FormsAuthentication.SetAuthCookie(thisUser.Username, true);
                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("GiveAccess", new { id = visitor.ID });
                }
            }
            return Content("Testing");
        }

GiveAccess方法

public ActionResult GiveAccess(int ID)
        {
            var user = _VisitorService.GetVisitor(ID);
            String[] roles = Roles.Provider.GetRolesForUser(user.Username);

            if(roles.Contains("Administrator"))
            {
                return RedirectToAction("SysUser", "Admin");
            }
            else
            {
                return RedirectToAction("Index", "Member");
            }
            //RedirectToAction("Index", "Member");
        }

的Web.config

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/User/Login"/>
    </authentication>
    <roleManager enabled="true" defaultProvider="TamilLeagueRoleProvider">
      <providers>
        <clear/>
        <add name="TamilLeagueRoleProvider" type="TamilLeague.WebUI.myRoleProvider" cacheRolesInCookie="false"/>
      </providers>
    </roleManager>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>

2 个答案:

答案 0 :(得分:0)

myRoleProvider中有一个无参数构造函数,它不会实例化服务。你确定班级没有进入那个构造函数吗?如果是,那么当您尝试使用该服务时,您将获得空引用异常。

答案 1 :(得分:0)

您无法通过构造函数将依赖项注入RoleProvider。换句话说,提供者模型现在不允许参数化构造函数。

要解决此问题,您需要使用Service Locator Pattern

例如,在Autofac中 -

private IVisitorService VisitorService { get; set; }

public MyRoleProvider()
{
   var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
   var cp = cpa.ContainerProvider;

   VisitorService = cp.RequestLifetime.Resolve<IVisitorService>();
}