简体   繁体   English

在ASP.NET Core中重写User.IsInRole

[英]Override User.IsInRole in ASP.NET Core

I've got an MVC 6 website (asp.net core/5) where I need to check if a user is in specific roles or not from the razor pages. 我有一个MVC 6网站(asp.net core / 5),在这里我需要从剃须刀页面检查用户是否处于特定角色。 Whenever I call User.IsInRole("{rolename}") , it returns false everytime. 每当我调用User.IsInRole("{rolename}") ,它每次都会返回false。 If I just call my RoleRepository it works just fine. 如果我只是调用RoleRepository,它就可以正常工作。

Do I need to override the User.IsInRole() functionality someplace, or is that method obsolete in ASP.NET Core? 我是否需要在某个地方重写User.IsInRole()功能,还是该方法在ASP.NET Core中已过时?

Here's my implementation so far: 到目前为止,这是我的实现:

        if (User.IsInRole("Admin") || User.IsInRole("SuperUser") || User.IsInRole("DataIntegrity"))
        {
            model.IsDataIntegrity = true;
        }

This works correctly when I call it via the Authorize policy, like this: 当我通过“授权”策略调用它时,它可以正常工作,如下所示:

    [Authorize("DataIntegrity")]
    [ValidateAntiForgeryToken]
    [HttpPost]
    [Route("team/edit/{schoolId:int:min(1)}/{schoolName?}")]
    public async Task<IActionResult> Edit(SchoolEditViewModel model)
    {
        model.SchoolInfo = await _schoolRepo.GetSchoolInfo(model.SchoolId, _currentSeason);

        IsModelValid(model);
        if (!ModelState.IsValid)
        {
            return View(await ApplyUnboundProperties(model));
        }

        await SaveSchool(model);

        return RedirectToAction("Live", "SchoolMain", new {schoolId = model.SchoolId, schoolName = model.SchoolInfo.SchoolName});
    }

More googling and here's what I found works for me: 谷歌搜索更多,这是我发现的功能:

Checking login user AuthorizePolicy in Razor page on Asp.Net Core 在Asp.Net Core的Razor页面中检查登录用户AuthorizePolicy

More specifically, I needed to inject the IAuthorizationService into my views (or controllers), and then call the AuthorizeAsync method. 更具体地说,我需要将IAuthorizationService注入到我的视图(或控制器)中,然后调用AuthorizeAsync方法。

(In View) (在视图中)

@inject IAuthorizationService AuthorizationService

...

@if (await AuthorizationService.AuthorizeAsync(User, "PolicyName"))
{
    <p>This paragraph is displayed because you fulfilled PolicyName.</p>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM