Over a million developers have joined DZone.

Tip Of The Day: Default User Roles in ASP.NET MVC4

DZone 's Guide to

Tip Of The Day: Default User Roles in ASP.NET MVC4

· ·
Free Resource

ASP.NET MVC is an extremely powerful framework, and the default website template offers a good set of capabilities to build a fully functional portal that can be customized on top of the existing implementation. 

One of the highlights of the default template is the user-based content separation - there is a built-in authentication mechanism that binds to a SQL database, that subsequently allows you to specify what content to display to what users. A question I was asked recently was whether there was a way to specify user roles without major additions to the existing web app skeleton, such as implementing a custom membership provider and fortunately the answer is yes.

Let's begin by establishing where the user role is assigned, and that is the registration stage. In the default template, you have the AccountController that contains a Register action. The default implementation looks like this:

public ActionResult Register(RegisterModel model)
    if (ModelState.IsValid)
        // Attempt to register the user
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            return RedirectToAction("Index", "Home");
        catch (MembershipCreateUserException e)
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));

    // If we got this far, something failed, redisplay form
    return View(model);

What's missing here is the role assignment, so let's add that. Right after the CreateUserAndAccount call, we can check whether a specific role exists, and if it is - add the registered user to it. In case the role is new, create it.

if (!Roles.RoleExists("Standard"))

Roles.AddUserToRole(model.UserName, "Standard");

Here I am working with a role called Standard, but obviously you can use another identifier for it. If you open the database that is carrying the app data, you will notice that there are two new tables introduced in the existing context - Roles and UsersInRoles.

As the data skeleton is established, you can now limit content access based on roles. In views, you could use the Authorize attribute:

[Authorize(Roles = "Admin")]

Or you could check for the role directly:

@if (Roles.GetRolesForUser().Contains("Admin"))

Simple as that.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}