How to Authorize in MVC 4.0 Razor

2019-04-10 13:49发布

问题:

Basically I want to add 2 view in my project/website. One for Admin and another for User. I already add [Authorize] tag in my target controller and it works.

After use [Authorize] tag when I try to insert something that time it redirect to registration page and any of the registration member can input data. But how can I specific an admin who can input data in table ??

I watch several tutorial and video but there working approach is not clear for me. In plural site video they use Seed data and write a method in there. But I input data in database. So, how can I work with this video tutorial ?? Because I don't have any seed data.

回答1:

You can restrict your user on view by just not showing html to him with simple if statement:

@if (User.IsInRole("Admin"))
{
   //here blocks that you want to show to users with Admin role   
}

Also you can decorate some specific actions with [Authorize] attribute like that:

[Authorize(Roles = "Admin")]
public ActionResult SaveTopSecret()
{

}

User.IsInRole("Admin") also available in the controller, so you can decide which view you want to show to which user:

public ActionResult Index()
{
    if(User.IsInRole("Admin"))
    {
        return View("Admin");
    }
    return View("User");
}


回答2:

@ if (User.IsInRole("Admin"))
{
     return RedirectToAction("Index","Home");
}
else
{
    return RedirectToAction("Index2","Home");
}

hope this works for you :)