A Simple ASP.NET vNext MVC Application without Visual Studio 2014 Part 1

There are already posts out there explaining how to setup ASP.NET vNext. The first and the foremost source, ASP.NET vNext Home in Github has all the steps clearly documented. Then, there is a ton of videos and good stuff out there. The objective of this post is to show the steps involved in setting up ASP.NET vNext and create a “complete” MVC application (remember MVC in vNext means MVC + Web API). Of course, we will not need to install VS 2014 but I don’t think it will be practical to do any serious development without VS. But then, just to get a taste of what vNext is, it is okay. Here are the steps (Windows only).

The very first step is getting the K Version Manager (KVM). Open a command prompt as admin and run the following PS command.

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))"

This downloads a couple of files (kvm.cmd and kvm.ps1) into the %USERPROFILE%\.kre\bin folder.

Now that we have KVM, next step is to install the K Runtime Environment (KRE). You can get the latest version of the run time by running the following command. Before you run this command, close the command prompt you have right now, where you ran the PS. Open a new one and run the command.

kvm upgrade

This downloads stuff into the %USERPROFILE%\.kre\packages folder. Now, you have the run time installed. To see what you got, use the following commamnd.

kvm list

That should produce an output like this.

Active   Version        Runtime   Architecture  Location                      Alias
------   -------        -------   ------------  --------                      -----
  *      1.0.0-alpha4   CLR       x86           C:\Users\you\.kre\packages    default

So, we now have the run time version 1.0.0-alpha4 and this is CLR, which means the desktop version. With vNext, there is another type called cloud optimized CLR. To get that, run the following command.

kvm install latest -runtime CoreCLR

If you do a kvm list now, the output will be like this.

Active   Version        Runtime   Architecture   Location                      Alias
------   -------        -------   ------------   --------                      -----
         1.0.0-alpha4   CLR       x86            C:\Users\you\.kre\packages    default
  *      1.0.0-alpha4   CoreCLR   x86            C:\Users\you\.kre\packages

Now, we also have the cloud-optimized CLR and it is active. Just for the heck of it, let us now go back to the desktop CLR. The command to make CLR runtime active will be this.

kvm use 1.0.0-alpha4 -runtime CLR

It’s time now to create our first ASP.NET vNext MVC app. Create a folder “HelloWorld” where ever you want. Create a file “project.json”, which is basically a text file and hence use the text editor of your choice.

{
    "dependencies": {
        "Microsoft.AspNet.Hosting": "1.0.0-alpha4",
        "Microsoft.AspNet.Mvc": "6.0.0-alpha4",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-alpha4"
    },
    "commands": {
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
    },
    "frameworks": {
        "aspnet50": { }
    }
}

We need three packages and that is all we specify in dependencies. Now, create a Startup.cs file like so.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use((context, next) =>
        {
           context.Response.ContentType = "text/plain";
           context.Response.WriteAsync("Hello ");

           return next.Invoke();
        });

        app.Run((HttpContext context) =>
        {
           return context.Response.WriteAsync("ASP.NET vNext");
        });
}

So, the folder “HelloWorld” will have two files – project.json and Startup.cs. In the command window, change the directory to this folder. Then, run the following command.

kpm restore

This command pulls down all the packages as defined by the project.json. To start the app, run the following command.

k web

If you see the “Started” message, you are all set to make a request. Open browser and go to http://localhost:5000. You should see the message “Hello ASP.NET vNext”.

With that, we have completed building and running our first ASP.NET vNext app. We currently have two vNext middleware componenets producing response but we have not added MVC yet into the mix. That’s what we do now. Add the following using directives to the Startup.cs.

using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Mvc;
using Microsoft.Framework.DependencyInjection;

Change the Startup class like so.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseServices(services =>
        {
            services.AddMvc();
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "Default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapRoute("ApiRoute", "{controller}/{id?}");
        });
    }
}

Create the usual MVC folder structure under HelloWorld and the files.

HelloWorld
    Controllers
        HomeController.cs
        ValuesController.cs
    Views
        Home
            Index.cshtml
        Shared
            _Layout.cshtml 

HomeController.cs

using Microsoft.AspNet.Mvc;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewBag.Message = "Hello ASP.NET vNext";
        return View();
    }
}

ValuesController.cs

using Microsoft.AspNet.Mvc;

public class ValuesController : Controller
{
    public Employee Get(string name)
    {
        return new Employee() { Name = name };
    }
}

public class Employee
{
    public string Name { get; set; }
}

Index.cshtml

@{
    Layout = "/Views/Shared/_Layout.cshtml";
}

<h1>@ViewBag.Message</h1>

_Layout.cshtml

<!DOCTYPE html>
<html>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Run “k web” (do a Ctrl+C and stop the previous instance if already running). If you issue a GET to http://localhost:5000, you should see Hello ASP.NET vNext. If you go a GET on http://localhost:5000/values?name=fowler, you should see an XML or JSON (depending on the browser). I use Chrome and I get this.

<Employee
  xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://schemas.datacontract.org/2004/07/">
<Name>fowler</Name>
</Employee>

Now, let us change Startup.cs and HomeController.cs, like so. Added an interface and a class implementing the interface.

public class HomeController : Controller
{
    private readonly IDataSource dataSource;

    public HomeController(IDataSource ds)
    {
        this.dataSource = ds;
    }

    public IActionResult Index()
    {
        ViewBag.Message = this.dataSource.GetMessage();
        return View();
    }
}

public interface IDataSource
{
    string GetMessage();
}

public class SillyDataSource : IDataSource
{
    public string GetMessage()
    {
        return "Hello ASP.NET vNext..";
    }
}

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseServices(services =>
        {
            // Added this line
            services.AddTransient<IDataSource, SillyDataSource>();

            services.AddMvc();
        });

        app.UseMvc(...); // No change
    }
}

Stop and do k web again. If you make a GET to http://localhost:5000, you will see Hello ASP.NET vNext... The message is from the data source class and since dependency injection is a first-class citizen in ASP.NET vNext and that it comes with a simple container out-of-box, we could resolve IDataSource to SillyDataSource without using any external container. More on DI here. So, we have a simple ASP.NET vNext MVC application in place. Just a starting point for anyone who wants to quickly setup an MVC app and get going.

In the next installment, we will see how to add cookie-based authentication.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s