【问题标题】:How to redirect from Identity Area to Admin in ASP.NET CORE 2如何在 ASP.NET CORE 2 中从身份区域重定向到管理员
【发布时间】:2018-11-25 22:38:45
【问题描述】:

我无法从身份区重定向:

if (role=="Admin")
                {

                    return RedirectToAction("Index","Home",new { Area=Input.Role ,id=9});
                }

到管理区域控制器-主页,操作-索引。始终将我重定向到身份区域中的索引;

【问题讨论】:

  • 那么用户认证了吗?用户是否已经在角色中? Input.Role 是什么?在我们弄清楚你有什么之前需要更多的背景故事......它是否在控制器中? <a asp-action="Index" asp-controller="Home" asp-area="Admin" asp-route-id="9">Admin Area</a>

标签: asp.net-core-mvc


【解决方案1】:

查看您的代码,对于有人会在登录时指定角色的原因,我仍然摸不着头脑。你能说出这背后的原因吗?

最简单的答案是与位于

中的 OnPostAsync(); 中的代码内联
//this because of the routes you have in StartUp.cs
[Authorize(Roles ="Admin")]
[Area("admin")]
public class HomeController : Controller
{          

    public IActionResult Index()
    {
        return View();
    }
}

Login.cs 页面...

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {

        returnUrl = returnUrl ?? Url.Content("~/");            

        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(Input.Username, Input.Password, Input.RememberMe, lockoutOnFailure: true);

            if (result.Succeeded)
            {
                var user = await userManager.GetUserAsync(User); // Claims Principle

                if (await userManager.IsInRoleAsync(user, "Admin"))
                {
                   //SIMPLEST ANSWER since you using mixed environment with PAGES
                   return LocalRedirect("~/admin");
                }

                //TODO:
                _logger.LogInformation("User logged in.");
                return LocalRedirect(returnUrl);
            }

【讨论】:

    【解决方案2】:

    下面一一检查你的问题:

    • 我收到错误A method 'CakeStore.App.Areas.Admin.Controllers.HomeController.Index (CakeStore.App)' must not define attribute routed actions and non attribute routed actions at the same time,您不应该同时定义[HttpGet(Name ="AdminPanel")][Route(nameof(Admin) + "/[controller]")]

      //[HttpGet(Name ="AdminPanel")]
      [Area(nameof(Admin))]
      [Route(nameof(Admin) + "/[controller]")]
      public IActionResult Index()
      {
          return View();
      }
      
    • 对于var role = this.roleManage.GetUrl(Input.Username);,它将通过用户名检索角色,检查您是否获得了预期的角色Admin

    • return RedirectToAction("Index","Home",new { Area=Input.Role ,id=9});,你没有在Index中定义id,不需要添加id路由。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 2019-05-08
      相关资源
      最近更新 更多