基于.NET Core 2 MVC角色的登录

时间:2017-12-08 16:26:47

标签: c# asp.net-mvc asp.net-core asp.net-identity

我有一个.NET Core 2 MVC项目,我的部分网站与我项目中的另一个完全分开。这两个“部分”共享同一组用户。 在项目的其中一个部分中,我希望用户能够看到登录页面,但只有具有特定角色的用户才能够实际登录。

目前我使用ASP.NET Identity的用户管理器的IsInRoleAsync方法,但我想知道是否有更好的解决方案呢?

由于

2 个答案:

答案 0 :(得分:0)

您可以使用Authorize属性:

public class AccountController : Controller
{   
    [HttpGet]
    public ActionResult Login()
    {
         // shows the login page
    }

    [HttpPost]
    [Authorize(Roles = "Administrator")]
    public ActionResult Login(LoginViewModel model)
    {
         // Process login
    }
}

答案 1 :(得分:0)

我认为你可以像这样使用你的代码:

[HttpPost]
public ActionResult Login(LoginViewModel model)
{
     // Process login
     // after he loged in
     // Check if he is an admin, if not log out using :
     await signInManager.SignOutAsync();
     // then redirect to login page with a message
}

我希望这适合你。