"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Part 4: Adding an Admin View

by Mike Wasson

Download Completed Project

Add an Admin View

Now we’ll turn to the client side, and add a page that can consume data from the Admin controller. The page will allow users to create, edit, or delete products, by sending AJAX requests to the controller.

In Solution Explorer, expand the Controllers folder and open the file named HomeController.cs. This file contains an MVC controller. Add a method named Admin:

[!code-csharpMain]

   1:  public ActionResult Admin()
   2:  {
   3:      string apiUri= Url.HttpRouteUrl("DefaultApi", new { controller = "admin", });
   4:      ViewBag.ApiUrl = new Uri(Request.Url, apiUri).AbsoluteUri.ToString();
   5:   
   6:      return View();
   7:  }

The HttpRouteUrl method creates the URI to the web API, and we store this in the view bag for later.

Next, position the text cursor within the Admin action method, then right-click and select Add View. This will bring up the Add View dialog.

In the Add View dialog, name the view “Admin”. Select the check box labeled Create a strongly-typed view. Under Model Class, select “Product (ProductStore.Models)”. Leave all the other options as their default values.

Clicking Add adds a file named Admin.cshtml under Views/Home. Open this file and add the following HTML. This HTML defines the structure of the page, but no functionality is wired up yet.

[!code-cshtmlMain]

   1:  <div class="content">
   2:      <div class="float-left">
   3:          <ul id="update-products">
   4:              <li>
   5:                  <div><div class="item">Product ID</div><span></span></div>
   6:                  <div><div class="item">Name</div> <input type="text" /></div> 
   7:                  <div><div class="item">Price ($)</div> <input type="text" /></div>
   8:                  <div><div class="item">Actual Cost ($)</div> <input type="text" /></div>
   9:                  <div>
  10:                      <input type="button" value="Update" />
  11:                      <input type="button" value="Delete Item" />
  12:                  </div>
  13:           </li>
  14:          </ul>
  15:      </div>
  16:   
  17:      <div class="float-right">
  18:      <h2>Add New Product</h2>
  19:      <form id="product">
  20:          @Html.ValidationSummary(true)
  21:          <fieldset>
  22:              <legend>Contact</legend>
  23:              @Html.EditorForModel()
  24:              <p>
  25:                  <input type="submit" value="Save" />
  26:              </p>
  27:          </fieldset>
  28:      </form>
  29:      </div>
  30:  </div>

In Solution Explorer, expand the Views folder and then expand the Shared folder. Open the file named _Layout.cshtml. Locate the ul element with id = “menu”, and an action link for the Admin view:

[!code-cshtmlMain]

   1:  <li>@Html.ActionLink("Admin", "Admin", "Home")</li>

[!NOTE] In the sample project, I made a few other cosmetic changes, such as replacing the string “Your logo here”. These don’t affect the functionality of the application. You can download the project and compare the files.

Run the application and click the “Admin” link that appears at the top of the home page. The Admin page should look like the following:

Right now, the page doesn’t do anything. In the next section, we’ll use Knockout.js to create a dynamic UI.

Add Authorization

The Admin page is currently accessible to anyone visiting the site. Let’s change this to restrict permission to administrators.

Start by adding an “Administrator” role and an administrator user. In Solution Explorer, expand the Filters folder and open the file named InitializeSimpleMembershipAttribute.cs. Locate the SimpleMembershipInitializer constructor. After the call to WebSecurity.InitializeDatabaseConnection, add the following code:

[!code-csharpMain]

   1:  const string adminRole = "Administrator";
   2:  const string adminName = "Administrator";
   3:   
   4:  if (!Roles.RoleExists(adminRole))
   5:  {
   6:      Roles.CreateRole(adminRole);
   7:  }
   8:  if (!WebSecurity.UserExists(adminName))
   9:  {
  10:      WebSecurity.CreateUserAndAccount(adminName, "password");
  11:      Roles.AddUserToRole(adminName, adminRole);
  12:  }

This is a quick-and-dirty way to add the “Administrator” role and create a user for the role.

In Solution Explorer, expand the Controllers folder and open the HomeController.cs file. Add the Authorize attribute to the Admin method.

[!code-csharpMain]

   1:  [Authorize(Roles="Administrator")]
   2:  public ActionResult Admin()
   3:  {
   4:      return View();
   5:  }

Open the AdminController.cs file and add the Authorize attribute to the entire AdminController class.

[!code-csharpMain]

   1:  [Authorize(Roles="Administrator")]
   2:  public class AdminController : ApiController
   3:  {
   4:      // ...

[!NOTE] MVC and Web API both define Authorize attributes, in different namespaces. MVC uses System.Web.Mvc.AuthorizeAttribute, while Web API uses System.Web.Http.AuthorizeAttribute.

Now only administrators can view the Admin page. Also, if you send an HTTP request to the Admin controller, the request must contain an authentication cookie. If not, the server sends an HTTP 401 (Unauthorized) response. You can see this in Fiddler by sending a GET request to http://localhost:*port*/api/admin.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/older-versions/using-web-api-1-with-entity-framework-5/using-web-api-with-entity-framework-part-4.htm
< THANKS ME>