开发者

How to display data based on roles in MVC?

I added the AuthorizeAttribute to secure my ActionResult.

[Authorize(Roles = "MyUser, Admin")]
    public ActionResult Index()
    {
        var allData = myDataRepository.FindAllData();
        return View(allData);
    开发者_StackOverflow中文版}

The Index view displays a list of data from my table. I want to show 1 row is the user Role is MyUser and all rows if the Role is Admin.

Is the correct (MVC) way just checking for the user Role and doing an if else?


I believe you are going to want to include the role limitation to your repository and allow that to determine what data to return.

var allData = myDataRepository.FindAllDataForRole(roleName);

Hal


If the User (or their role) is a proper domain object to you, and is altering the results of your Index() method, then the Index method itself should take said user as a parameter, first off.

The Authorize filter is about whether the person should be able to execute a given action at all, not about what data they can see in that action.

As Hal said, the user's role should then be applied as a criteria in your query of the repository, or perhaps apply the user itself as a criteria (if, for example, a single user has rights by several roles plus individual user rights).

Something like this, then:

[Authorize(Roles="MyUser, Admin")]
public ViewResult Index(User user)
{
     return View(repo.GetDataForUser(user));
}

Then, inside your repository's GetDataForUser method, you do whatever filtering on rights or whatever.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜