In 99% of cases, static files you want served for your website will be able to live in the wwwroot folder. But in that rare 1% use case that you need to have static files littered throughout your project (Or you dislike having a wwwroot folder nonstop!), what can you do?

First off, you will need the StaticFiles nuget package to be able to serve files at all. So run the following from your nuget package manager :

In your startup.cs, you would typically see something similar to the following where the “UseStaticFiles” call allows you to serve files from your wwwroot folder :

But you can actually add multiple calls to StaticFiles each with it’s own file location :

We leave the original StaticFiles call in there so that the wwwroot is still used to serve static files if we want (Although if you are intending to never use it, you can remove that call completely), but we can add subsequent calls to the middleware for each additional static content folder.

The FileProvider parameter tells the middleware where it can find the physical files, and the RequestPath is the actual URL that a browser should go to to reach the static files. In this example if we we went to something like www.mysite.com/content/js/site.js, we would be served static files.

Modifying the RequestPath can come in handy, consider the following :

In this example our physical folder hasn’t changed, but the request path is now simply /js rather than /content/js. You can use this to essentially rewrite public urls for your static content (Which can come in handy if you end up moving around the actual physical folder).

If you’re up to date on your dotnet tooling, then you are probably using the very latest Dotnet Nuget command (dotnet add package). And then on top of that you are wondering where the hell are all your packages, and where is your packages.config? I know atleast for me it was extremely confusing adding a nuget package and not seeing a packages folder fill up. So let’s run through some of the changes.

What Is The Dotnet CLI Command “dotnet add package” Actually Doing?

So when you run the command “dotnet add package”, what is it doing under the hood? Well actually, when it boils down to it, it’s actually just forwarding your command to the “nuget.exe” anyway. If you dig into the source code eventually you end up at a class called “NugetForwardingApp” (Source) that takes your dotnet command and transforms it to the original nuget command anyway. This makes sense as nuget will still be used with the .net full framework so it’s pointless for the .net core team to completely rebuild a package manager from scratch right?

As a side note, you’ll often find this with dotnet CLI commands. Often they are just a wrapper or a skin over things like nuget or msbuild to make your life a little easier (Because who hasn’t wasted a day trying to get a finicky msbuild command to work!).

Where Is My packages.config?

Previously when you added a nuget package, you would end up with a packages.config file in the root of your project directory that told nuget what dependencies you had. You’ll quickly notice that this is not the case anymore, so where are your dependencies defined? In the .csproj of course. Let’s say I create a new project with a reference to EntityFramework, my csproj would look a bit like the following :

The csproj format that is used for .net core projects is now very very clean, so it makes viewing your dependencies as easy as viewing your packages.json. The other benefit is that you have all your dependencies in a single file. When you add project references (Or hardcoded DLL references), it’s all contained within the csproj.

Where Is My Packages Folder?

You are probably used to having a packages folder in your solution that holds the nuget downloads. This is now gone and been replaced by a global packages folder. By default this is located at “%userprofile%\.nuget\packages”. Opening this folder the first time might give you a heart attack with how much is in here, and I suspect that “cleaning” this folder in the future is going to be the fix for various bugs.

It certainly makes sense to have a global folder on some levels though as for many projects you will be using the exact same version of the same library across many projects. With ASP.net core itself being inside nuget, it also makes sense to not have to download this over and over for each project.

It’s also important to note that the location of “%userprofile%\.nuget\packages” is just the default, you are able to edit your nuget.config either on the global level or per project level to specify another location. But be aware if you do this on the project level and give each project it’s own packages folder, you will download all of ASP.net core into that packages folder all over again.

What Happens When I Publish?

When it comes to publishing, there is really nothing to worry about. When you publish, .net core works out what packages you need and moves them into your publish destination folder for a stand alone solution. You don’t for example need this packages folder on your server, it’s only for development purposes.

Editing Nuget.config

As discussed earlier, you can edit your nuget.config file to change your local global cache location, add nuget feeds, and configure other settings such as HTTP Proxies, default package versions etc. The Microsoft documentation for editing your nuget.config can be found here. A handy tip to generating a nuget file at the project level is the following command from a command line/bash/terminal.

Be aware that adding a nuget file at the project level (even a completely empty one) can have bad side effects. I’ve found that settings don’t exactly “fall through”, e.g. If a setting is missing from the project level nuget.config, it doesn’t then go to the global config, it just treats it as false/missing etc.

C# as a language has always been well respected, but convincing developers who traditionally develop on Macs and Linux machines to swap to a windows box was always a tough sell. While there has been Mono, developing on a non windows machine was pretty much always a non starter. With .net core, not only are you able to run your apps cross platform, but the tooling has improved to the point where you can actually develop on a non windows machine pretty painlessly.

One such option is to use VS Code to develop in. VS Code is a mix of “editor” like simplicity (so something like Sublime), but also with the power of Visual Studio. If you are in love with Visual Studio, then it may seem a bit more “restrictive” (certainly VS Code doesn’t carry the bloat of Studio), but it makes up for it in speed and ease of use. What’s also great is that if you have a mix of developers who like developing on Windows, Mac and Linux, you can have a consistent IDE across the team.

Getting Started

First up go ahead and install VS Code

Then you will still need to install the .net Core SDK. The tooling is cross platform, but make sure you download the correct SDK for your machine. It’s possible (Especially on Windows), that you may need a restart of your machine after installing the SDK.

Go ahead and open up VS Code now. On the left hand menu hit the icon labelled extensions or you can press Ctrl + Shift + X. This should open up the extensions menu where you can install additional plugins to VS Code. Remember, VS Code on it’s own is extremely light and is basically a notepad editor. To be able to use intellisense and debugging, we need to install a couple of extras.

On the extensions menu, go ahead and install the C# addon. After hitting the install button you need to also click “reload” which reboots the editor.

Creating A .Net Core Project

VS Code itself doesn’t deal with project templating. If you are used to Visual Studio where you can create new projects within the IDE, this may be a bit painful to get used to. Instead you need to create your projects from the command line. Go ahead and create a folder on your machine where you want to have your work live (In the examples below, I created a folder called “VSCodeExample”, use this if you want to follow along at home). Open a command prompt/bash/terminal, and move to this directory.

First we need to create a “solution” which is essentially going to be our container for holding all our projects. A “solution” file is a bit like a .project file if you are coming from Eclipse. It’s a one stop shop for opening an entire “solution” and knowing all the projects that are part of it. In truth, when using VS Code you actually don’t need a solution file at all, you instead are opening the “folder”. But there are two main reasons for still creating it.

  • If you have other developers that are using Visual Studio, then this makes their lives a hell of a lot easier (Infact, you will need a solution file to make it work at all).
  • Build commands can point to a solution now instead of a project which means that you can build a “set” of projects just by pointing your build at the solution file.

We are going to create a solution file and that’s that!

In your command prompt type :

This creates a new solution file ready to be used. It should also be noted the .sln file is also named the same as it’s parent folder.

Go ahead now and create another folder inside your existing workspace, and call it the name of your desired “project”. In this case, I’m going to go ahead and call mine “VSCodeExample.Web”. Your “solution” directory should now look like this :

OK, now take your command prompt and move into your project folder (VSCodeExample.Web), and type :

This creates a new MVC project that is pretty similar (If not identical), to what Visual Studio would create for you. It basically lays down all the boilerplate code so you can jump right in and start working.

It should be noted that typing “dotnet new -all” will list off all templates that are available to you. In our case we went with an MVC template, but you can do things like Web API templates, Console apps and class libraries.

OK, now remember what I said about being a great neighbour with the solution file? Move your command prompt up a level to your solution directory and type the following :

What this does is add your project into the solution file so that when someone comes along and opens it in Visual Studio, they are right up to speed. Again, it’s not required for working in VS Code but is still a nice habit to get into.

Finally, we need to go ahead and restore some packages that our projects need. In your command prompt from inside the solution folder, run the following :

This restores nuget packages that are missing from your project. If you aren’t sure what the hell nuget is, just follow along for now and it will be explained further later!

Let’s go ahead and open our new baby up in VS Code. In VS Code go File -> Open Folder and select your “solution” folder. The first time you open a new .net core project, You will see the following bar come across the top of your screen.

Pressing yes on this creates a launch.json and a tasks.json file inside your solution. These are used to be able to launch and debug your project from VS Code. You can create these manually and edit them, but it’s easier just to let VS Code handle this for us, so click Yes.

On your tree menu, go into your new web project -> Controllers -> Home Controller and have a play around. You will quickly notice that all the intellisense, syntax highlighting,  and annoying warnings that you know and love from Visual Studio are here.

Running Your Project In VS Code

This is going to be a pretty short section. Simply press F5 in VS Code to have your project launch. Any build errors will need to be resolved before launching your project, but otherwise a new browser window/tab should open with your project running in it. Breakpoints in VS Code all work as per normal, and things such as callstack, watches, output console etc are all there too.

There is however one small bug. If you get the following message “Could not find the prelaunch task build”. The first thing you should do is try and close VS Code and reopen it again. As stupid as this sounds, this happens on new projects all the time and it’s resolved with a quick open and close!

Managing Nuget Packages

Nuget is the package system for .net. If you’ve used NPM, Bower or Composer before, it’s all pretty similar.

Now if you have used Nuget before, in the latest version there are numerous changes like no more packages.config, no more local cache of packages (There is now a global cache per machine), and many other changes. There are too many new things to really put in this article, but it is worth going and having a read on what you can expect.

To add a package to your project, you now have to use the command line (Which isn’t as scary as you might think!). If we wanted to add the “Newtonsoft.Json” package to our project, we would run the following in the project folder :

This will add the reference in your csproj, then run a “restore” on your project to ensure you have the package in your global cache. If you check inside your csproj file for your project, you should see something similar to the following :

You can actually add and remove references to nuget packages directly in the csproj file if you think it’s going to be easier, but remember from the command line you need to run “dotnet restore” to ensure that you have all the packages required. It can be easier when you are trying to consolidate multiple projects to the same nuget package version to just go ahead and edit the project file directly rather than hand typing the dotnet add command in your console.

Adding Project References

In any project larger than a “Hello World”, you are going to be building class libraries that need to be referenced from other projects in your solution Again, another Visual Studio sugar that you are going to miss when moving to VS Code. Luckily there is a dotnet command for that!

The exact command is

Or in our example app. I have added a new project called “VSCodeExample.Library”, and I’m going to add it to my web project. I run the following from my solution directory.

When I open up my VSCodeExample.Web.csproj I now see the following :

And again, you can add this project reference directly in your csproj if you prefer it that way. There is no magic going on behind the scenes when you run the dotnet command, it literally just adds that XML.

Anything Else?

No doubt I’ve missed a couple of things that are specific to your project. The best advice I can give is to do a quick scan on the dotnet command list here. You don’t need to read in depth on every single command, but when you get into a jam it usually gives you a lightbulb moment of “Yeah… I think I remember there was a dotnet command for that…”. And as always, drop a comment below if you get stuck with anything else!

Google have recently released support for ASP.net core on their “GCloud” hosting platform. And along with it released some documentation on how to get up and running here. The documentation itself uses their container engine, but you can actually get up and going on GCloud a lot faster using a couple of command line tools (Very similar to how you might get going on Azure). So for this tutorial instead we will try and get up and running much faster, and then you can transition to container hosting if it fits your needs better.

Something super important is that at the time of writing, GCloud only supports .net core 1.0 (Not 1.1). Ensure that your apps are running on .net core 1.0 before attempting to deploy them!

Note : This tutorial uses Windows Powershell a lot. If you are on Mac and Linux that could be an issue! But the commands will be very very similar if not exactly the same in your own native command line. 

Setting Up GCloud

First install the GCloud SDK from here https://cloud.google.com/sdk/. This gives you a few extra powershell/cmd commands to be able to deploy straight from your desktop (And obviously in the future from your build server). Be sure to install the “beta” components along the way too (You will see this inside the installer). More than likely after installing you will have to restart your machine, if the powershell commands don’t work off the bat you might want to first try rebooting (It is Windows after all).

If you haven’t already head to Google Cloud at https://cloud.google.com/ and sign up. It’s free! You can read more about the limits of the free tier here. But for the purpose of this tutorial there is no way you are going to blow through the free hosting.

Once you are signed up and in, create your first project on the dashboard. Name it whatever you want – I went with “My First Project”.

Now, here it gets a little difficult but you should be able to handle it! Open a powershell prompt and type :

A browser window should open instantly on your machine asking you to login to your Google cloud account and give permission to access your GCloud account. After following the prompts your powershell window should have something similar to the following in it :

Great! You are now logged into your account. On your GCloud dashboard in your browser, you should see something similar to :

Take the ProjectID and type the following into your Powershell window

Now we are set up to deploy from Powershell!

Setting Up Your ASP.net Core Project

For this tutorial I’m just using a basic hello world app (The default empty project from Visual Studio), but it really shouldn’t matter what your app is doing.

Add a file to your project called “app.yaml”. This is information for GCloud to work out how your app should be run. Inside the app.yaml file put the following :

After creating this file you need to set it to copy to the output directory. If you are on project.json this means opening up your project.json file, and finding the publishOptions node. It should end up looking like this :

If you are on the latest version of .net core tooling (e.g. csproj), then you need to set the file to copy always in Visual Studio by right clicking the file, selecting properties, and then changing the drop down to Copy Always.

Again, another reminder that GCloud only supports .net core 1.0 (Not 1.1). This means that you must target 1.0 and not 1.1. Unfortunately switching around between .net core versions is another kettle of fish that deserves it’s own post really. Have a quick google around for how to switch around .net core targeting versions if you are not already using 1.0.

Deployment

Now onto deployment. For my test application I’m going to do a simple dotnet publish, but you may have something more complicated going on so you might want to read the docs here. But for now, let’s just run the following inside our project directory from Powershell.

Take your powershell and move into your release directory. The path will be something like “bin\Release\netcoreapp1.0\publish”.

Run the following command from powershell :

This is basically the entire deploy process. You are telling GCloud to take everything inside that folder (Along with the app.yaml file describing what it is), and push it to your logged in project.

If this is your first time deploying, you will be asked which region you wish to deploy to, and then it will take a good 5 – 10 minutes for the deployment to complete. Just hang in there! Once complete, you should be able to type the following powershell command which will open your newly deployed app in your browser!

Moving Forward

The first thing you should learn is how to switch off your running instance. It’s sort of buried a bit behind layers of menus, but this link should take you directly there : https://console.cloud.google.com/appengine/versions. Select the latest version of your app (If you’ve only deployed once, then there will only be one), and hit stop up top.

Before you switch it off though, take a look around the portal and check out some of the awesome features like logging (Direct Kestrel logging which is pretty nifty), and monitoring. Both of which look very very good.

Drop a comment below with your experience getting up and running on GCloud!

While .net core ships with the service collection dependency injection framework as a first class citizen, some developers may still prefer to stick with their third party DI framework they used in full framework .net. And for good reason, the .net core DI is rather basic when it comes to options for injecting and auto binding. Things like auto binding all interfaces, or being able to inject different services based on parameter names, class names etc are all lost.

Luckily Autofac, LightInject, DryIOC and StructureMap do have the ability to be used in .net core (With others slowly making the move), but there are a couple of gotchas that you need to go through. Namely you have to remember that things like IOptions, ILogger, HttpContext and other framework classes need to be available in the DI framework by default. On top of that, libraries that already use the ServiceCollection of .net core need to be able to be dropped in and used as per normal.

Almost all third party DI frameworks have adopted the same pattern for .net core. The general steps for any third party DI library are :

  • ConfigureServices in your startup.cs file should return IServiceProvider not void
  • You should register framework services as you normally would within the .net core service collection
  • Build your IOC container and register services as normal
  • Push the .net core services collection into the IOC container
  • Build your container and return the service provider

Sound complicated? Don’t worry, sample code will be provided for each DI framework as well as any other gotchas you have.

Autofac In ASP.net Core

First install the following Nuget package :

Here is the code for your startup.cs :

DryIOC In ASP.net Core

First install the following Nuget package :

DryIOC prefers to keep it’s registrations out of the startup.cs file (Which is probably a good idea). So create a class called “CompositionRoot”, that has a constructor that takes IRegistrator, and register your services inside there.

Then your startup.cs should look like the following :

LightInject In ASP.net Core

First install the following Nuget package :

Here is the code for your startup.cs:

StructureMap In ASP.net Core

First install the following Nuget package :

Note I also had an issue where I had to install StructureMap itself manually for some reason. If things aren’t working correctly (e.g. Intellisense is going wild), install the following Nuget package.

StructureMap is another IOC container that prefers a separate class(s) to handle your registrations. Let’s just create a simple ServicesRegistry class.

In your startup.cs add the following :

Unity In ASP.net Core

Unity is close to being dead in the water. It would appear according this Github issue that .net core support won’t be coming any time soon.

Windsor In ASP.net Core

At the time of writing, Windsor does not have support for ASP.net core. You can follow the progress in the Github Issue here.

Ninject In ASP.net Core

At the time of writing, Ninject does not have support for ASP.net core

If you’ve never used a dependency injection framework before, then the new Services DI built into .net core could be a bit daunting. Most of all, understanding the differences between transient, singleton and scoped service registrations can be easy to begin with, but tough to master. It seems simple on the service, “register this interface as this service”, but there is a couple of gotchas along the way. Hopefully after reading this, you will have a better grasp on the different types of lifetimes you can use within your application, and when to use each one.

Transient Lifetime

If in doubt, make it transient. That’s really what it comes down to. Adding a transient service means that each time the service is requested, a new instance is created.

In the example below, I have created a simple service named “MyService” and added an interface. I register the service as transient and ask for the instance twice. In this case I am asking for it manually, but in most cases you will be asking for the service in the constructor of a controller/class.

This passes with flying colors. The instances are not the same and the .net core DI framework creates a new instance each time. If you were creating instances of services manually in your code without a DI framework, then transient lifetime is going to be pretty close to a drop in.

One thing that I should add is that there was a time when it was all the rage to stop using Transient lifetimes, and try and move towards using singletons (Explained below). The thinking was that instantiating a new instance each time a service was requested was a performance hit. Personally in my experience this only happened on huge monoliths with massive/complex dependency trees. The majority of cases that I saw trying to avoid Transient lifetimes ended up breaking functionality because using Singletons didn’t function how they thought it would. I would say if you are having performance issues, look elsewhere.

Singleton Lifetime

A singleton is an instance that will last the entire lifetime of the application. In web terms, it means that after the initial request of the service, every subsequent request will use the same instance. This also means it spans across web requests (So if two different users hit your website, the code still uses the same instance). The easiest way to think of a singleton is if you had a static variable in a class, it is a single value across multiple instances.

Using our example from above :

We are now adding our service as a singleton and our Assert statement from before now blows up because the two instances are actually the same!

Now why would you ever want this? For the most part, it’s great to use when you need to “share” data inside a class across multiple requests because a singleton holds “state” for the lifetime of the application. The best example was when I needed to “route” requests in a round robin type fashion. Using a singleton, I can easily manage this because every request is using the same instance.

Transient Inside Singletons

Now the topic of “transient inside singletons” probably deserves it’s own entire article. It’s the number one bug when people start introducing singletons to their applications. Consider the following two classes.

So we have two services, one named “MySingletonService” and one named “MyTransientService” inside it.

Then our services registration looks like the following.

If we ran this, what could we expect? It actually blows up on the second Assert. But why? In our very first example at the top of the page, when we registered a service as Transient they weren’t the same but now they are? What gives?!

The reason lies in the wording of how DI works. Transient creates a new instance of the service each time the service is requested. When we first request an instance of the parent class as singleton, it creates that instance and all it’s dependencies (In this case our transient class). The second time we request that singleton class, it’s already been created for us and so doesn’t go down the tree creating dependencies, it simply hands us the first instance back. Doh! This is also true of other types of lifetimes like scoped inside singletons.

Where does this really bite you? In my worst experience with Singletons, someone had decided the smart thing to do in their application was make the entire service layer singletons. But what that meant was that all the database repository code, entity framework contexts, and many other classes that should really be transient in nature then became a single instance being passed around between requests.

Again, use Singleton if you have a real use for it. Don’t make things singleton because you think it’s going to save on performance.

Scoped Lifetime

Scoped lifetime objects often get simplified down to “one instance per web request”, but it’s actually a lot more nuanced than that. Admittedly in most cases, you can think of scoped objects being per web request. So common things you might see is a DBContext being created once per web request, or NHibernate contexts being created once so that you can have the entire request wrapped in a transaction. Another extremely common use for scoped lifetime objects is when you want to create a per request cache.

Scoped lifetime actually means that within a created “scope” objects will be the same instance. It just so happens that within .net core, it wraps a request within a “scope”, but you can actually create scopes manually. For example :

In this example, the two scoped objects aren’t the same because created each object within their own “scope”. Typically in a simple .net core CRUD API, you aren’t going to be manually creating scopes like this. But it can come to the rescue in large batch jobs where you want to “ditch” the scope each loop for example.

Instance Lifetime

In early versions of .net core (And other DI frameworks), there was an “Instance” lifetime. This allowed you to create the instance of a class instead of letting the DI framework build it. But what this actually meant was that it essentially became a “singleton” anyway because it was only “created” once. Because of this Microsoft removed the Instance lifetime and recommended you just use AddSingleton like the following.

 

Logging in any application is always a contentious issue with many developers rolling their own framework and tacking on third party libraries such as Nlog or Log4net. While these approaches are fine, Microsoft have come in and made logging a first class citizen in ASP.net core. What that means is a standardized way of logging that is both simple and easy to get up and running, but also extensible when you have more complicated logging needs.

The Basics

This guide assumes you have a basic project up and running (Even just a hello world app), just to test how logging works. For getting up and running, we are going to use the debug logger. For that, you need to install the following Nuget package :

In your startup.cs file, in the Configure method, you need to add a call to AddDebug on your logger factory. This may already be done for you depending on which code template you are using, but in the end it should end up looking a bit like the following :

Let’s try this out first. Run your web project and view any URL. Back in Visual Studio you should view the “Output” window. If you can’t see it, go Debug -> Windows -> Output. After viewing any URL you should see something pretty similar to :

The content isn’t too important at this stage, but the import thing is that you are seeing logging in action! Of course it is a bit verbose and over the top, but we will be able to filter these out later.

That sort of automatic logging is great, but what we really want is to be able to log things ourselves. Things like logging an exception or fatal error that someone should look into immediately. Let’s go into our controller. First we need to add a dependency on ILogger in our constructor and then we need to actually log something. In the end it looks a bit like this :

Great, now when we go into this action what do we see in the debug window?

You will notice that our log messages are shown with the level that they are logged at, in this case Information and Error. At this point it doesn’t make too much a difference but it will do in our next section.

See how easy that was? No more fiddling around with nuget packages and building abstractions, the framework has done it all for you.

Logging Levels

The thing is, if we rolled this into production (And used a logger that pushes to the database), we are going to get inundated with logging about every single request that’s coming through. It creates noise that means you can’t find the logs you need, and worse, it may even cause a performance issue with that many writes.

An interesting thing about even the Microsoft packaged loggers is that there isn’t necessarily a pattern for defining their configuration. Some prefer full configuration classes where you an edit each and every detail, others prefer a simple LogLevel enum passed in and that’s it.

Since we are using the DebugLogger, we need to change our loggerFactor.AddDebug method a bit.

What this says is please only log to the debug window errors we find. In this case we have hardcoded the level, but in a real application we would likely read an appSetting that was easily changeable between development and production environments.

Using the same HomeController that we used in the first section of this article, let’s run our app again. What do we see in the debug window?

So we see it logging our error message but not our information message or the system messages about pages being loaded. Great!

Again, It’s important to note that each logger may have their own configuration object that they use to describe logging levels. This can be a huge pain when swapping between loggers, but it’s all usually contained within your startup.cs.

Logging Filters

Most (if not all) loggerFactory extensions accept a lambda that allows you to filter out logs you don’t want, or to add extra restrictions on your logging.

I’ll change the AddDebug call to the following :

In this case, “category” stands for our logging category which in real terms is the full name (Namespace + Class) of where the logger is being used. In this case we have locked it down to HomeController, but we could just as easily lock it to “LoggingExample”, the name of this test app. Or “Controllers”, the name of a folder (And in the namespace) in our example app.

Under this example and running our code again, we see that we log everything from the controller (Information & Error), but we log nothing from the system itself (Page requests etc).

What you will quickly find is that this Lambda will get crazy big and hard to manage. Luckily the LoggerFactory also has an extra method to deal with this situation.

Using this, you can specify what level of logging you want for each category. LogLevel.None specifies that you shouldn’t log anything.

Framework Loggers

ASP.net Core has a set of inbuilt loggers that you can make use of.

AddConsole
Writes output to a console. Has serious performance issues in production so only to be used in development.

AddDebug
What we have used above! Writes output to the debugger. Again, a dev only tool.

AddEventSource
Only available on Windows, writes events out to an ETL. You generally need to use a third party tool such as PerfView to be able to read the logs.

AddEventLog
Writes out logging to the EventLog (Windows only). Again, pretty nifty for logging errors especially when you have a devops team looking after the boxes, they like seeing issues in the Event Log!

AddAzureWebAppDiagnostic
If you are on Azure, this writes out logs to Azure diagnostics. This is very handy and if you are in Azure, it’s a must do as other types of logging (Such as to a database), may fail because of network issues which are causing the errors in the first place.

Third Party Loggers

NLog
https://github.com/NLog/NLog.Extensions.Logging – NLog is usually my go to for the simple fact that it in turn has many extensions into things like Logentries. Obviously there are other more simple options such as logging to a file or sending an email.

Elmah
https://github.com/elmahio/Elmah.Io.Extensions.Logging – Elmah is mostly popular because of the dashboard that it comes with. If you are already using Elmah, then this is an easy slot in.

Serilog
https://github.com/serilog/serilog-extensions-logging – Serilog is gaining in popularity. Again, another easy extension to get going that has a lot of versatility.

Anyone that has used the full .net MVC framework has spent many an hour trying to rejig the web.config and custom MVC filters to get custom error pages going. Often it would lead you on a wild goose chase around Stack Overflow finding answers that went something along the lines of “just do this one super easy thing and it will work”… It never worked.

.net Core has completely re-invented how custom errors work. Partly because with no web.config, any XML configuration is out the window, and partly because the new “middleware pipeline” mostly does away with the plethora of MVC filters you had to use in the past.

Developer Exception Page

The developer exception page is more or less the error page you used to see in full .net framework if you had custom errors off. That is, you could see the stack trace of the error and other important info to help you debug the issue.

By default, new ASP.net core templates come with this turned on when creating a new project. You can check this by looking at the Configure method of your startup.cs file. It should look pretty close to the following.

Note that checking if the environment is development is so important! Just like the CustomErrors tag in the full framework, you only want to leak out your stacktrace and other sensitive info if you are debugging this locally or you specifically need to see what’s going on for testing purposes. Under no circumstances should you just turn on the “UseDeveloperExceptionPage” middleware without first making sure you are working locally (Or some other specific condition).

Another important thing to note is that as always, the ordering of your middleware matters. Ensure that you are adding the Developer Exception Page middleware before you are going into MVC. Without it, MVC (Or any other middleware in your pipeline), can short circuit the process without it ever reaching the Developer Exception page code.

If your code encounters an exception now, you should see something similar to the following :

As we can see, we get the full stack as well as being able to see any query we sent, cookies and other headers. Again, not things we want to start leaking out all over the place.

Exception Handler Page

ASP.net core comes with a catch all middleware that handles all exceptions and will redirect the user to a particular error page. This is pretty similar to the default redirect in the CustomErrors attribute in web.config or the HandleError attribute in full framework MVC. An important note is that this is an “exception” handler. Other status code errors (404 for example) do not get caught and redirected using this middleware.

The pattern is usually to show the developer error page when in the development environment, otherwise to redirect to the error page. So it might look a bit like this :

You would then need to create an action to handle the error. One very important thing to note is that the ExceptionHandler will be called with the same HTTP Verb as the original request. e.g. If the exception happened on a Post request, then your handler at /home/error should be able to accept Posts.

What this means in practice is that you should not decorate your action with any particular HTTP verb, just allow it to accept them all.

Statuscode Pages

ASP.net core comes with an inbuilt middleware that allows you to capture other types of HTTP status codes (Other than say 500), and be able to show them certain content based on the status code.

There are actually two different ways to get this going. The first is :

Using “StatusCodePagesWithRedirects” you redirect the user to the status page. The issue with this is that the client is returned a 302 and not the original status code (For example a 404). Another issue is that if the exception is somewhere in your pipeline you are essentially restarting the pipeline again (And it could throw the same issue up).

The second option is :

Using ReExecute, your original response code is returned but the content of the response is from your specified handler. This means that 404’s will be treated as such by spiders and browsers, but it still allows you to display some custom content (Such as a nice 404 page for a user).

Custom Middleware

Remember that you can always create custom middleware to handle any exception/status code in your pipeline. Here is an example of a very simple middleware to handle a 404 status code.

On our way back out (Remember, the code after the “next” is code to be run on the way out of the pipeline), we check if the status code was 404, if it is then we return a nice little message letting people know we 404’d.

If you want more info on how to create a custom middleware to handle exceptions (Including how to write a nice class to wrap it), check out our tutorial on writing custom middleware in asp.net core.

Yeoman is a code scaffolding tool that generates boilerplate project code for you. If you’ve been developing on Windows for some time, you’re probably using Visual Studio to create your projects, and letting it generate your “base” code. For the most part, if you’re still on Windows and still use Visual Studio, Yeoman may not be for you (But it’s still not totally out of the question!). If you’re on Linux, or prefer building in a minimalistic scenario using something like VS Code, then Yeoman can do a lot of the legwork for you.

Getting Started

The template we are going to use in this tutorial utilizes the bower package manager. If you don’t have this, or ff you don’t know what this is, you are going to have to install it. Run the following from a command prompt/terminal to install Bower.

Yeoman is actually an NPM module so if you haven’t already, you will need to install NodeJS from here. Once you’ve got Node up and running, you need to run the following command from a command prompt (Or terminal on non Windows), to install Yeoman globally.

Now while Yeoman is a scaffolding tool, the templates it uses to actually generate the code are mostly community driven. You can find all possible generators on this page here. While this tutorial focussesd on using Yeoman with .net core, it can be used to scaffold any codebase in any language. The generator we will be using is called “generator-aspnet”. For this, we need to install the template using NPM. So run the following in a terminal/command prompt.

Great, now we are ready to go!

Go create a folder for your project now. Open a command prompt/terminal inside this folder and run

All going well, you should be presented with a screen that is similar to this (Note it can take a while for things to kick into gear, just be patient!)

Select “Web Application” (Not Empty). On the next screen select the Bootstrap framework, type your project name in and let rip. You will see Yeoman go ahead and create your project similar to how Visual Studio would do it, you can then open up your project folder and see this :

As you probably saw, there are a tonne of templates built in to do most of the legwork of project creation for you. Have a play around creating different project types and see what is generated for you. Again, if you are using Visual Studio as your IDE, then most of this won’t be that amazing, but if you are going without, then having something to generate all this code for you is a godsend.

Using Other Templates

As quickly discussed above, this aspnet generator isn’t the only template for .net core in Yeoman. If you had over here, and type in .net core you will find several generators that can be used. Many of which are the basic template but with slight additions such as using Angular 2 instead of 1.6.

One template that is very popular is one by Microsoft called “aspnetcore-spa”. You can find out more info over on the Github page, but in short it’s a code template for creating single page apps.

Creating Your Own Templates

If you are a vendor and find yourself creating (for lack of a better term), “cookie cutter” type websites where there are many similarities, you might actually want to create your own custom template to create consistency. It’s not quite as straight forward as throwing something in a directory and having Yeoman copy/paste it, but it’s definitely worth investigating if you find yourself creating boilerplate code time and time again. You can read more in the official Yeoman docs.

NancyFX (Or Nancy, FX stands for framework), is a super lightweight web framework that can be used to spin up minimalist API’s in no time at all. It’s mostly seen as an alternative to Web API when you don’t need all the plumbing and boilerplate work of a full Web API project. It also has a lot of popularity with NodeJS developers that are used to very simple DSL’s to build API’s.

Getting Started

When creating a new project, you want to create a .net core web project but make sure it’s created as an “empty” application. If you select Web API (Or MVC) it brings along with it a ton of references and boilerplate code that you won’t need when using Nancy.

You will need the Nancy Nuget package so run the following from your package manager console. At this point in time the .net core able Nancy is in Pre-Release, so at the time of writing, you will need the pre flag when installing from Nuget.

In your startup.cs you need to add a call to UseNancy in the Configure method. Note that any other handler in here (Like AddMVC) may screw up your pipeline, especially when it comes to routing. If you are intending to use Nancy it’s probably better to go all in and not try and mix and match frameworks.

If you have issues with the line “UseOwin” then you will need to install the Owin package.

Instead of creating a class that inherits from “Controller” as you normally would in Web API, create a class that inherits from “NancyModule”. All your work is then actually done in the constructor, which may seem a bit weird at first but when you are building a tiny API it actually becomes nice to keep things to a minimum. Our NancyModule that we will use for the tutorial looks a bit like this

It should be pretty self-explanatory. But let’s go through each one.

  1. When I go to “/” I will see the text “Hello World”.
  2. When I go to “/SayHello?name=wade” I will see “Hello wade”
  3. When I go to “/SayHello2/wade” I will see “Hello wade”

As you can probably see, Nancy is extremely good for simple API’s such as lookup type queries.

Model Binding

While you can stick with using dynamic objects, model binding is always a nice addition. Below is an example of how to model bind on a POST request.

Using Postman I can send a request to /login as a form encoded request, and I can see I get the correct response back :

Nancy also recognizes different body types. If you send the request as JSON (With the appropriate header of “Content Type:application.json”), Nancy will still be able to bind the model.

Before and After Hooks

Before and after hooks are sort of like MVC filters whereby you can intercept the request before and after your Nancy Module has run. Note that this is still part of the .net core middleware pipeline so you can still add custom .net core middleware to your application along side Nancy hooks.

An important thing with hooks is that they are per module. They live within the module and are only run on requests routed to that module, any requests that land on other modules don’t run the before hook. The hook itself tends to point to a method elsewhere, so in the end it works out a bit like a controller attribute.

There are two ways a hook can handle a request. Here’s one way :

If a hook returns null as above, code execution is passed down to the matching route. For example, if you are checking the existence of a particular header (API key or the like), and it’s there, then returning null simply allows execution to continue. Compare this to the following :

In this example, if our header collection doesn’t contain our API key (Weak security I know!), we return a response of “Request Denied” and execution ends right there. If the header is there, we continue execution.

View Engine

While Nancy predominately is used for lightweight API’s, there is an inbuilt view engine and you can even get an addon that allows for Razor-like syntax – In fact it’s pretty much identical to Razor. The actual package can be found here. Unfortunately, at this time the view engine has a dependency on the full .net framework so cannot be used in a web application targeting .net core.

Static Content

Nancy by default won’t serve static content. It does have its own way of dealing with static content and various conventions, but I actually prefer to stick with the standard ASP.net core middleware for static files. This way it short-circuits Nancy completely and avoids going down the Nancy pipeline. For that you can install the following nuget package :

In the Startup.cs class in the Configure method, add a call to UseStaticFiles like so :

Place all your static content in the wwwroot (CSS, Images, Javascript etc), and you will now be able to have these files served outside the Nancy pipeline.

Everything Else

Nancy has it’s own documentation here that you can take a read through. Some of it is pretty verbose, and you also have to remember that not all of it is applicable to .net core. Like the static content section above, there may be an existing solution with .net core that works better out of the box or is easier to configure. As always, drop a comment below to show off your new project you built in Nancy!