本文介绍了ASP.NET MVC自定义RoleProvider无法从数据库中为用户名检索角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我似乎无法找到上述问题的正确解决方案.我不断收到System.NullReferenceException: Object reference not set to an instance of an object.

i cant seem to find the right solution for the above issue. I keep getting 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);

The error message is from my custom roleprovider from the GetRolesForUser(string username) at line var user = _VisitorService.GetVisitors().FirstOrDefault(u => u.Username == username);

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

The VisitorService works in the Controller but not in the RoleProvider.

下面是代码,请根据需要提供建议.预先谢谢你.

below are the code please advice as required. Thanks you in advance.

自定义RoleProvider

Custom 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方法

GiveAccess method

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

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>

推荐答案

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

You cannot inject dependencies to RoleProvider via constructor. In other words, Provider Model doesn't now allow parameterized constructor.

为了解决该问题,您想使用服务定位器模式.

In order to solve it, you want to use Service Locator Pattern.

例如,在Autofac中-

For example, in Autofac -

private IVisitorService VisitorService { get; set; }

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

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

这篇关于ASP.NET MVC自定义RoleProvider无法从数据库中为用户名检索角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:23