.NET Core 1.0 release – what you need to know to get started

| 7 min. (1404 words)

With the recent release of .NET Core 1.0 and the corresponding MVC framework update for it, many of you may be interested in migrating existing web projects or starting a greenfields one with it. What will soon become apparent is that it’s a pretty huge overhaul and different in many places from MVC 5.

In general, it brings fresh ideas and tooling from the open source world (especially NodeJS) to the Microsoft ecosystem. It’s a fast and intuitive framework that mostly just works (once you figure out the differences.) Aside from the tooling refresh, the fact that it targets all platforms is a win and worth a look for all developers, no matter what ecosystem they hail from.

The fact that C# and the CLR can now be developed on OS X and deployed to Linux is pretty sweet. It’s worth remembering that the new .NET Core 1.0 release is a large change and is quite different. Some old ways will need to be relearned at first, so it’s worth noting how the initial commit of a new .NET Core 1.0 project might look compared to the past.

Setting up as local development site

.NET Core uses its web server, Kestrel, to serve up CLR code. We are using the traditional IIS workflow to forward requests through to Kestrel. In order for IIS to handle HTTP requests to your .NET Core app code, you’ll need to install the .NET Core Windows Server Hosting bundle. This contains the ASP.NET Core Module and creates a reverse proxy between IIS and the Kestrel server.

Create a local dev website in IIS like normal:

  1. Hit Win+R, open ‘inetmgr’, then right click Sites -> Add Website.
  2. Add a site name e.g sample.local and set its physical path to your project’s folder (the one with web.config in it). Set the host name to a domain such as sample.local.
  3. Add the above domain to your HOSTS file, pointing it at 127.0.0.1.

The Publishing to IIS documentation is quite useful as it lists all the steps involved. In particular check out the ‘Common Errors’ section as there are a few possible failure states depending on what you have installed or built, it will also highlight whether or not the various moving parts can locate what they need.

In particular, to debug the config, you’ll want to check these two:

  • Enable stdout logging: create a log/ directory in your project root (where web.config is), and set stdoutLogEnabled to true in the web.config
  • Check the Event Viewer: Win+R -> eventvwr then look under Applications.

There is one additional step which involves ‘Publishing’ the project to generate the assemblies alongside the app code. You can set this target folder to one outside the project, or within it and point Kestrel at the release folder. Then, you only need to right-click on the project in VS once and click ‘Publish’, setting its Target Location to File System and .\bin\Release\PublishOutput. You can then develop your site in VS. Changes will be reflected upon save, as normal.

After you’ve published your site point, finally the aspNetCore element in web.config at that location. Your line should look something like this:

<aspNetCore
  processPath="dotnet"
  arguments=".\bin\release\publishoutput\SampleApp.dll"
  stdoutLogEnabled="true"
  stdoutLogFile=".\logs\stdout"
  forwardWindowsAuthToken="false" />

If you’ve published it to another outside folder, the ‘arguments’ value would be .\SampleApp.dll or if it’s a standalone .exe leave it blank.

Finally, run up your domain in a web browser, and start developing! The following is a series of common web development tasks that need to be set up in a new project. They will help you get up to speed with .NET Core 1.0.

Common client-side tasks

Serving static content

The default projects have static assets (JS/CSS/images) wired up and ready for routing straight out the box. These now reside in wwwroot/ by default, beneath your project directory. Using the Gulp or Grunt plugins to rebuild the assets is the easiest way to develop these. Have them updated upon file saves , either using a file watch or the Task Runner Explorer. The project templates or Yeoman can include these config files (such as yo aspnet --gulp). Here’s how to set up the workflow from scratch:

  1. Add the NPM package.json and gulpfile.js or Gruntfile using Add New Item in the Solution Explorer.
  2. Open up Task Runner Explorer by right-clicking on the Gulp or Grunt config file, then clicking Run on the selected task.
  3. Add the particular dependencies for Gulp/Grunt.

The project defaults to pointing at the site.css/site.js files if the environment is Development, or site.css.min/site.js.min if it’s Staging or Production (case-insensitive). If the environment is pointing at either of the latter two you’ll need to run the Minify tasks with or Gulp/Grunt to update the client-side assets. If you’re pointed at dev the assets will update in place.

There are a couple of ways to set the development environment. If you’re running Kestrel from VS, you can set it by right-clicking on the project in VS then going to Debug and setting the ASPNETCORE_ENVIRONMENT value. Alternatively, you can set the same in Properties -> launchSettings.json. If you’re running it in IIS and want to set it in the web.config, you can do this like so:

<aspNetCore ...>
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
  </environmentVariables>
</aspNetCore>

Finally, ensure app.UseStaticFiles(); is present in the Startup.Configure method. There are also richer alternatives available including UseFileServer which enables directory browsing (not by default as it’s a security hole).

Bundling client-side assets in .NET Core 1.0

Once you’ve got one of the above client-side task runners set up, traditional bundling and minification is available using their standard pipelines such as gulp-concat and UglifyJS2 (called using its wrapper libraries). Excellent documentation for this is available here. If you’re up for the more cutting edge client-side package management like Webpack, continue on with the next section.

Client-side package management with Webpack

A more cutting edge approach to the above for development is available. One popularized and especially useful with React applications is Webpack. A NuGet package is available here that supports this from .NET Core 1.0. This gets a development server for Hot Reload for rapid iteration of modules and pages – when code is updated and saved, the changes are immediately reflected in the browser without a static page load.

Webpack is powerful and also provides the ability for production bundles to use async loading of dependencies when they’re needed (‘Hot Reload’ is the killer feature for me).

Common server-side tasks

URL routing

Fortunately, the URL routing in .NET Core MVC isn’t very different from MVC 5. The declarative catch-all routes are now specified in Startup.cs with the app.UseMvc() lambda function. The default Controller and Action method routing thus works out of the box as before.

The upshot of this is bog-standard MVC – a FooController that inherits from Controller, with a Bar method that returns an ActionResult and a View(). This will load the view located in Views\Foo\Bar.cshtml when /foo/bar is requested by a user agent.

Attribute routing is also supported. The following method will return when ‘/baz’ is requested:

public class FooController : Controller
{
    [Route("/baz")]
    public ActionResult Bar()
    {
      return View();
    }
}

Areas

Area folders work as before, too, so you can group up related Controllers and Views into sections. For instance when using the default route mapping you can add areas like this:

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

Logging

The ILoggerFactory that gets passed in to Startup.Configure lets you configure the available logger targets and the verbosity level (with LogLevel) etc.

To log out messages you then accept an instance of ILogger where T is the instantiating class type. Storing this in an instance variable then lets you call _logger.LogDebug() and similar.

Rendering partials

Since the update, if you attempt to render a Partial view from a Razor view with @Html.RenderPartial it chokes. The syntax has changed slightly and the async-await everywhere API appears to be preferred. The following syntax works correctly instead:

@{await Html.RenderPartialAsync("Partial"); }

That will render Partial.cshtml using the normal lookup rules (current directory upwards).

It’s over!

We hoped you found this post useful and enjoy looking into .NET Core 1.0. Add Raygun Crash Reporting and Pulse to your site after you’ve got everything up to make sure things run smoothly. Install the NuGet package Mindscape.Raygun4Net.AspNetCore in Visual Studio by right-clicking on your project -> Manage NuGet Packages.

Have questions on the .NET Core 1.0 release and what it means for you? Comment below!