Membership roles made easy with Razor syntax in WebMatrix
Let’s see how easy it is to restrict access to certain pages based on roles.
First, if you don’t have WebMatrix, DOWNLOAD IT HERE. I am using the WebMatrix 2 Beta version released in September 2011.
We’re going to use the photo gallery site created in a previous post as a starting point.
First Run your website from WebMatrix and click Login.
Click Register.
Create an account by entering an email and password. Notice the photo gallery template has CAPTCHA verification built-in, so you can tell whether a user is a human or computer by asking the user to read and enter extra words that a computer wouldn’t be able to read.
All you would need to do is uncomment out the corresponding code in Register.cshtml and replace the public and private keys, and register at reCAPTCHA.net
Notice under Databases, your newly created account is now under UserProfiles. Take note of the UserId.
In your Databases, under webpages_Roles, type in a role name under RoleName (e.g. admin).
Hitting <Enter> will automatically assign a RoleId. Remember this role ID.
Double-click webpages_UsersInRole. We would like to assign our user with UserId 1 to the admin role, which corresponds to RoleId 1. Enter these corresponding ID numbers to assign the user to the desired role.
Now we’re going to exit our Databases and go back Files. Right-click on your website name and create a New File…
Create a CSHTML file called AdminOnly.cshtml. This will be the file only a user who is an admin can access.
Create another file and name it AdminError.cshtml. This will be the file to which the user who is not allowed to access the previous file gets redirected.
Enter the following Razor syntax (or some variation thereof using your friend, IntelliSense) into your AdminOnly.cshtml file:
@if (Roles.IsUserInRole(“admin”))
{<span>welcome to the jungle </span>}
else
{Response.Redirect(“~/AdminError”);}
Enter the following Razor syntax (or some variation) into your AdminError.cshtml file:
<p>You must log in as an admin to access that page.</p>
Save both files. Now try to access https://localhost:xxxx/AdminOnly (the local URL and xxxx can be found under Site above Files, Databases, and Reports or when you hit Run).
Log out of the admin account and try to access the same URL.