net HttpContext.用户返回错误的对象类型



我有一个使用MVC的c#在VS开发的web应用程序,我有一个自定义角色提供程序。这种方法已经成功运作了好几年。当需要时,使用以下命令检查角色:

[HttpPost]
[CustomAuthorize(Roles = "admin, dataPerinatal, perinatalAllCases")]
public ActionResult PerinatalDataEntrySummary()
{
    IPrincipal principal = HttpContext.User;
    bool isAdmin = false;
    bool canViewAll = false;
    if (principal.IsInRole("admin"))
    {
        isAdmin = true;
    }
    else if (principal.IsInRole("perinatalAllCases"))
    {
        canViewAll = true;
    }
    // ....
}

返回principal作为System.Security.Principal.GenericPrincipal类型的对象。

然而,我刚刚在相同的控制器中添加了一个方法,并使用相同的代码来获得principal
[HttpPost]
public ActionResult FindCaseFromID(string nIMACHCaseID, string mBRRACECaseID)
{
    principal = HttpContext.User
    bool canViewAll = false;
    if (principal.IsInRole("perinatalAllCases")) 
    { canViewAll = true; }
     // ....
}

但是,这返回principal作为System.Web.Security.RolePrincipal类型的对象。这将使用AspNetSqlRoleProvider,并导致以下问题:

  1. 应用程序在没有安装SQL Express服务器的系统上生成'cannot find SQL server'错误
  2. 安装SQL Express Server的地方,IsInRole总是返回false

我如何确保HttpContext.User的每个实例都返回我需要的对象类型?为什么第二个实例返回不同的对象类型,而其他一切似乎是相同的?

答案原来是一个简单的代码错误。我所有的控制器都有一个自定义属性[CustomAuthorize]

[CustomAuthorize]
public class MyController : Controller

在属性类中创建HttpContext.User

初始方法的属性包含角色检查(见上文),但是该属性在整个类声明中缺失,因此第二个方法使用默认角色提供程序。一旦我添加了属性,问题就消失了。

最新更新