R – attribute for .net MVC controller action method

asp.net-mvcauthenticationmembership-providerroleprovider

Essentially I want to show a friendly message when someone is not part of a role listed in my attribute. Currently my application just spits the user back to the log in screen. I've read a few posts that talk about creating a custom attribute that just extends [AuthorizeAttribute], but I'm thinking there's got to be something out of the box to do this?

can someone please point me in the right direction of where I need to look to not have it send the user to the log in form, but rather just shoot them a "not authorized" message?

Best Answer

If simplicity or total control of the logic is what you want you can call this in your action method:

User.IsInRole("NameOfRole");

It returns a bool and you can do the rest of your logic depending on that result.

Another one that I've used in some cases is:

System.Web.Security.Roles.GetRolesForUser();

I think that returns a string[] but don't quote me on that.

EDIT: An example always helps...

public ActionResult AddUser()
{
    if(User.IsInRoles("SuperUser")
    {
        return View("AddUser");
    }
    else
    {
        return View("SorryWrongRole");
    }
}

As long as your return type is "ActionResult" you could return any of the accepted return types (ViewResult, PartialViewResult, RedirectResult, JsonResult...)