[英]User.IsInRole returns nothing in ASP.NET Core (Repository Pattern implemented)
[英]Override User.IsInRole in ASP.NET Core
我有一個MVC 6網站(asp.net core / 5),在這里我需要從剃須刀頁面檢查用戶是否處於特定角色。 每當我調用User.IsInRole("{rolename}")
,它每次都會返回false。 如果我只是調用RoleRepository,它就可以正常工作。
我是否需要在某個地方重寫User.IsInRole()
功能,還是該方法在ASP.NET Core中已過時?
到目前為止,這是我的實現:
if (User.IsInRole("Admin") || User.IsInRole("SuperUser") || User.IsInRole("DataIntegrity"))
{
model.IsDataIntegrity = true;
}
當我通過“授權”策略調用它時,它可以正常工作,如下所示:
[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});
}
谷歌搜索更多,這是我發現的功能:
在Asp.Net Core的Razor頁面中檢查登錄用戶AuthorizePolicy
更具體地說,我需要將IAuthorizationService注入到我的視圖(或控制器)中,然后調用AuthorizeAsync方法。
(在視圖中)
@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.