ASP.NET MVC Authorized Roles with HasAccesss from View
We are using the attribute [Authorize (Roles="yadda, yadda2")]
on our controllers and I am wondering if there is a built-in mechanism to detect if they have access after that from the view?
[Authorize (Roles="System Administrator, Administrator")]
public abstract class OperationsBaseContoller : BaseController
{
// omitted
}
// some view
@if(HasAccessTo<OperationsBaseController>())
{
<a href="#somewhereInOperations">Operations Action</a>
<a href="#anotherInOps">Example</a>
<a href="#oneMore">filler</a>
}
Something like the above would be great, so I could avoid providing links that cannot be delivered to them anyway. I do NOT , however I want the list of available roles in the view to be in again User.IsInRole("....")
, as it seems like a nightmare to maintain / duplicate code. I figured that if they give us an attribute, they also provide a built-in way to validate it from the view.
If not (couldn't find it on my own) I'll write mine but would like to avoid potential rethinking of wheels.
source to share
There are several useful extension methods that do exactly this
Html.ActionAuthorized
Html.ActionLinkAuthorized
published in
http://vivien-chevallier.com/Articles/create-an-authorized-action-link-extension-for-aspnet-mvc-3
In this article, I will explain how to create an action link extension that is authorization so that we can hide or disable an action link based on its authority.
source to share