MVC Music Store Sample Application
Overview
The MVC Music Store is a lightweight sample store implementation which sells music albums online, and implements basic site administration, user sign-in, and shopping cart functionality. You can find the MVC 3 version here, but in this tutorial you can play with the MVC 6 (ASP.NET vNext) version!Set Up the Environment
The first thing you need to do is set up the tools to build and run an application.Go to the aspnet/Home GitHub repository and follow the instructions under Getting Started. This will install the K Version Manager (KVM) and K Runtime (KRE).
Get the Code
The application code is hosted at GitHub.com. You can get it using the following steps:- Navigate
to the ASP.NET vNext repository on github.com:
https://github.com/aspnet/Home - Either clone the repository or download and unzip the Home-master.zip file.
- In the command prompt, run the following commands:
cd <HOME_REPOSITORY_ROOT> kvm setup Kvm install 1.0.0-alpha2
- Navigate to the MusicStore repository: https://github.com/aspnet/MusicStore
- Either clone the repository or download and unzip the MusicStore-master.zip file.
- In the same command prompt where you ran
kvm install
, run the following commands:cd <MUSICSTORE_REPOSITORY_ROOT>\src\MusicStore kpm restore
- Once you finish running the commands, you will be able to run the application in ASP.NET vNext.
What’s Inside
You will see the following folders:- MusicStore Contains all the project files for the MusicStore application written for MVC 6.
- MusicStore.Spa Contains a single-page application (SPA) implementation of MusicStore using MVC 6.
- MvcMusicStore Contains the MVC 5 version of MusicStore. It’s included here for you to conveniently compare with the MVC 6 version.
- MvcMusicStore.Spa Contains a SPA implementation of MvcMusicStore using MVC 5.
See It in Action
With the included scripts, you can run this application in three ways, as described in the table below. From the command line, run the respective command from <MUSICSTORE_REPOSITORY_ROOT>\src\MusicStore\.Method | Command-line Command | Default URL |
---|---|---|
In IIS Express | helios.cmd |
http://localhost:5001 (specified in script) |
Self-host | k web
|
http://localhost:5002 (specified in project.json) |
Hosted in a console application | k run
|
http://localhost:5003 (specified in project.json) |
Project Highlights
Notice first that the folder structure looks very similar to the ASP.NET MVC Web applications that you’re used to, with controllers and views. The Views folder even has the same folder structure as seen in earlier ASP.NET MVC versions. However, the project has the following changes:- There is no longer Global.asax
- Web.config files are used only for running the application in IIS Express
- .NET Framework and project dependencies are defined in project.json
- Application configuration such as HTTP services (such as MVC) and database settings are hooked up in the Startup.cs file
- There is also a Program.cs file for running MusicStore as a console application
public void Configure(IBuilder app) {}When running MusicStore as a console application, the following code in Program.cs likewise looks for the same Startup class to configure the Web application:
var engine = services.GetService<IHostingEngine>();
Code Highlights
Startup.cs
In ASP.NET vNext, Web applications are no longer dependent on System.Web namespaces. This change enables you to slim down your Web applications, so that you can add only the HTTP services you need to the application deployment, making your application as lean and fast as possible.Open <root>\src\MusicStore\Startup.cs in a text editor or Visual Studio. In the app.UseServices method invocation, find the following line:
services.AddMvc();This line adds MVC 6 to the application. Look up a few lines and down a few lines to see that services such as configuration, logging, Entity Framework, and ASP.NET Identity are added in the same fashion. Other than that, no other HTTP services are added to run this particular application.
Then, find the following lines of code:
app.UseMvc(routes => { routes.MapRoute( null, "{controller}/{action}", new { controller = "Home", action = "Index" }); });This is where you can add more routes to your Web application.
Coding Pattern for Multiple Environments
Go back to the top of <root>\src\MusicStore\Startup.cs and find the following code snippet:var configuration = new Configuration(); configuration.AddJsonFile("LocalConfig.json"); configuration.AddEnvironmentVariables(); services.AddInstance<IConfiguration>(configuration);This snippet demonstrates a new coding pattern possible in ASP.NET vNext that you can use to code once and deploy to multiple environments. When you develop your application locally, you can use application settings present in a local configuration file, such as LocalConfig.json in this case. But when you publish this application to a Windows Azure website, the line
configuration.AddEnvironmentVariables();causes the settings defined in Windows Azure to override the previously set values (set by
configuration.AddJsonFile
). In this way, you can make your application work in both your development
environment and your deployment environment without changing your code.No System.Web.* Dependencies
Open <root>\src\MusicStore\Controllers\HomeController.cs. The controller code is still the same as in previous versions, except that you don’t see any reference to the namespaces System.Web and System.Web.* any more, as mentioned previously. In place of System.Web.Mvc, you find Microsoft.AspNet.Mvc.using Microsoft.AspNet.Mvc; using MusicStore.Models; using System.Collections.Generic; using System.Linq;
View Components
In MVC 6, the new way for adding reusable components is called View Components. View components are functionally equivalent to child actions in previous MVC versions, but now separates the concept from controller action invocation. Let's compare the MusicStore code between MVC 5 and MVC 6.First, let's look at how this is done in MVC 5. In the MvcMusicStore project, which is the MusicStore application before being rewritten for ASP.NET vNext, open <root>\src\MvcMusicStore\Controllers\ShoppingCartController.cs and find the CartSummary action method. See that it is decorated with ChildActionOnly and returns the CartSummary partial view.
[ChildActionOnly] public ActionResult CartSummary() { var cart = ShoppingCart.GetCart(_storeContext, this); var cartItems = cart.GetCartItems() .Select(a => a.Album.Title) .OrderBy(x => x) .ToList(); ViewBag.CartCount = cartItems.Count(); ViewBag.CartSummary = string.Join("\n", cartItems.Distinct()); return PartialView("CartSummary"); }Reference that with Views\Shared\_Layout.cshtml where you’ll find how the child action gets invoked:
@Html.Action("CartSummary", "ShoppingCart")
Now let's look at the MVC 6 version. Open the file
<root>\src\MusicStore\Components\CartSummaryComponent.cs and note that this same reusable component
is now no longer part of the controller action invocation, but is now its own
class, which inherits ViewComponent.[ViewComponent(Name = "CartSummary")] public class CartSummaryComponent : ViewComponent { ... }Reference that with Views\Shared\_Layout.cshtml where you’ll find how the view component gets invoked:
@await Component.InvokeAsync("CartSummary")
Claims Authorization
Also new in MVC 6 is a claims-enabled authorization filter. Open <root>\src\MusicStore\Controllers\StoreManagerController.cs and see the following decoration for the StoreManagerController class:[Authorize("ManageStore", "Allowed")]This decoration authorizes any claims principal that has a claim with the type of ManageStore and the value of Allowed.
To see how the site administrator acquires this claim, open Startup.cs and find the following line in the CreateAdminUser method:
await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
Additional Resources
- Getting Started with ASP.NET vNext and Visual Studio "14"
- Introduction to ASP.NET vNext
- ASP.NET vNext Preview
- Download the Visual Studio “14” CTP
- Learn more about what’s in the Visual Studio “14” CTP
- Bug Tracker application
- Publishing MVC Music Store sample to Windows Azure Websites
- Set up Git on your dev machine