How to handle action based permissions in MVC

2019-08-07 06:30发布

I'm new to MVC and I would like to get suggestions on how to best handle action based permissions in my application.

I currently have some global permissions being checked at the controller level which work fine for rendering views the current user has access to, etc.

However, once the view has been rendered, I want to make decisions such as 'enable DELETE button, ONLY IF user has delete permissions for the item currently selected' At that point, those permissions are no longer Global but based on the context of the object selected.

How should I write my code to handle this type of scenario?

1条回答
聊天终结者
2楼-- · 2019-08-07 07:22

By Default your Views have access to the User Object.

You can check on the View if User.IsInRole("myDeleteRole").

or

@if(User.IsInRole("MyDeleteRole"))
{
<input type="subtmt" value="Delete">
}

I don't know if this is the best way, but its what i have done in the past

I guess another way would be to write seperate Views depending on what rights a user has. that way you could do the logic on the controller and send the user to the specified view

if(User.IsInRole("MyDeleteRole")
{
return View("MyDeleteView", vm)
}
else
{
return View("NoDeleteView", vm)
}
查看更多
登录 后发表回答