如何在ASP.NET CORE 2中从身份区域重定向到管理员

时间:2018-11-25 22:38:45

标签: asp.net-core-mvc

我无法从身份区域重定向:

if (role=="Admin")
                {

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

到管理区域Controller-Home,操作索引。始终将我重定向到身份区域中的索引;

2 个答案:

答案 0 :(得分:0)

看着您的代码,我仍在摸索要有人登录时指定角色的原因。您能否阐明其背后的原因?

最简单的答案与位于

中的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);
            }

答案 1 :(得分:0)

逐一检查您的问题:

  • 我收到错误let x = { id: "checkout", name: "git checkout", description: "checkout repository" }; let renamed = Object.entries(x).reduce((u, [n, v]) => { u[`__${n}`] = v; return u; }, {}); ,您不应同时定义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});,因此无需添加id路由。