ASP.net core comes with two ways to do authentication out of the box. The first is using ASP.net cores “identity” service that wraps a MSSQL set of tables and allows you to get every piece of functionality out of the box, but does require you to have a very rigid structure and do things the “Microsoft” way. It also requires you to use a database adapter that has been pre-built (Typically this means using Microsoft SQL). If you are using something like a NoSQL database store to your users, or you authenticate your users using something other than a username password combination, then using the full identity service can be a bit of a pain.

The alternative is to use ASP.net Core’s “Cookie Authentication” which allows you to use cookie based claims for a user, but authenticate the users yourself using your own data store, however that may work. That’s what this article is going to focus on.

Setup

If you are creating a brand new project using Visual Studio for this tutorial, ensure that when creating your project you select the “authentication type” to be none. We essentially want to start with a clean slate.

In your nuget package manager window, install the following package :

In your startup.cs file, find your configure method. You should add the following code to your pipeline but you must ensure this is before your call to “AddMvc”. This is extremely important. Your pipeline runs in the order you have added it so you need to obviously have authorization run before MVC kicks in.

A little bit about the options we have set here.

AuthenticationScheme is just the name we have given this instance of authentication. You can actually have multiple authentication middleware in your application. The name isn’t too important and can be anything if you are only having the single login.

LoginPath is the path to your login page

AccessDeniedPath is the path to a “denied” page

AutomaticAuthenticate means that the middleware runs automatically on every request and tries to authenticate the user

AutomaticChallenge means that a user should automatically be routed to the LoginPage if the user is not authorized.

Registering A User

Using Cookie Authentication as a simple middleware and not using the full identity service means you need to organize registering users and creating them in your data store yourself. There is nothing in the middleware to help you out there.

Logging In A User

For logging in, we will create a simple post model to accept our username and password combination.

I’ve created a controller called “AccountController”. Inside I’ve created a GET and POST endpoint for our model. The GET endpoint returns a view that has a simple form for logging in, the POST endpoint is where we do our work.

Let’s walk through that code a little.

First we validate the user. In our example we just validate every user but obviously in real life this would go away to our data store and validate the user/password combination.

Next we create a Claims list. These are things we know about the user that we wish to store on the cookie. In this example I’ve just stored the Username as the “Name” claim. This one is slightly important as we see later as there is a shortcut to get this name, but you can actually store any key/value combination inside the claims if you don’t want to have to go back to the database each time to get info on the logged in user.

We then build an identity, a principal, and then set the cookie using the SignInAsync method. There is a bit of cruft going on here in terms of building the identity and principal, but the important part is building claims and calling signin.

Authorizing Controllers

Next we obviously need to learn how to “lockdown” certain areas of our website to force a user to have to login. We can do this simply by adding an “Authorize” attribute to any controller.

And that’s all there is to it! Any user that navigates to this controller will be redirected to your “Logon” url.

Logging Our A User

Logging out a user is very simple.

That’s really all there is too it! Remember the Authentication Scheme you use here must match the one you set in the middleware setup.

Viewing The Logged In User

Obviously at some point we will want to view the logged in user, either to get further details about the user from the database or set onscreen elements in a view. Here we have some example code on how we can get both the username we set earlier, and any other claim we may have set.

The Name on the Identity object is just a fancy way of getting the “Name” claim that we set earlier, but for any other claim you can work with the claims list and fetch our data. Remember this will only be set after logging in so null checks should be done along the way.

Microsoft has released an urgent patch to various packages in .net core. If you are using any of the following packages directly, or any packages you use are also dependent on these packages you should update them immediately. You can read the full advisory on Github here.

Package Affected Versions Fixed Versions
System.Text.Encodings.Web 4.0.0
4.3.0
4.0.1
4.3.1
System.Net.Http 4.1.1
4.3.1
4.1.2
4.3.2
System.Net.Http.WinHttpHandler 4.0.1
4.3.0
4.0.2
4.3.1
System.Net.Security 4.0.0
4.3.0
4.0.1
4.3.1
System.Net.WebSockets.Client 4.0.0
4.3.0
4.0.1
4.3.1
Microsoft.AspNetCore.Mvc 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Core 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Abstractions 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.ApiExplorer 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Cors 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.DataAnnotations 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Formatters.Json 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Formatters.Xml 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Localization 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Razor.Host 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.Razor 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.TagHelpers 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.ViewFeatures 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3
Microsoft.AspNetCore.Mvc.WebApiCompatShim 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2
1.0.4
1.1.3

Fixing Direct Dependencies

To fix direct dependencies, you should simply open your csproj file for your project and check package references for the ones above. If you find any, then you should update to the fixed package version and redeploy immediately if your project is in production.

For example if you had the following csproj file :

The package for Microsoft.AspNetCore version 1.0.3 is vulnerable. Update the version to 1.0.4.

Fixing Transitive Dependencies

Transitive dependencies are dependencies of libraries that you are directly using. These are harder to track down but still simple to fix.

Open your project.assets.json file for your project (Should be in your project folder). Search inside this file for any dependencies that match the vulnerable package list above. If you find a vulnerable package, you need to manually add a reference to the fixed package in your csproj. The csproj version will override any transitive dependencies from other libraries (think of it like version forwarding in web.configs).

Fixing Project.Json (Legacy .net Core Apps)

If you have a .net core web app that is still on project.json, the process is much the same. For more info read the full advisory on Github here.

Migrating a project.json .net core project to the latest csproj format can be a bit of a minefield. There are a few gotchas and even best practices that you likely did when using a project.json based project that will actually make the migration to csproj fail.

But first, why should you not upgrade :

  • Your team is not ready to use Visual Studio 2017 (e.g. no licenses). csproj based projects can only be opened in Visual Studio 2017, they cannot be opened in Visual Studio 2015
  • Your team is using another IDE such as Jetbrains Ryder that does not have support (Or complete support yet) for csproj based projects.

If those aren’t you, then it is really a no brainer to upgrade your project to the latest .net core tooling.

One important thing to note is that tooling is not the same as the .net core version. Tooling refers to things like project.json vs csproj and how the .net core CLI works. It does not refer to the version of .net core (1.0 or 1.1). Updating the tooling does not change the version of the actual .net core runtime!

Preparation

You should go ahead and download the latest .net core SDK. If this is your first time doing this you should first read this article on how to run two versions of the .net core SDK side by side. This is really important if you intend to work on both project.json and csproj projects on the same machine for some time as you could end up not being able to open projects without the right global.json setup.

On the project you wish to migrate, check the root of your project/solution for a global.json file. This file is used to determine which SDK to use but annoyingly can cause havoc when you are trying to migrate. The reason being when you wish to migrate, you want to be able to run the migrate command using the latest tooling, but the global.json may point to an older version. If you try to migrate with this going on you will see the following error message :

Take a backup of the global.json and delete it from the root folder.

Using the Command Line

The command we are going to run from the command line is “dotnet migrate“. If we move our command line to the solution directory and run it, it will recursively move down into our projects and migrate them all to the csproj format.

It really is as simple as that!

Remember to create a global.json file in the root of our directory specifying what tooling version we are now on. This is actually an un-needed step realistically, but if you upgrade your tooling again on your machine you will want this project to be unaffected. It’s also handy when setting up a new developers machine to be able to remember which version of the SDK you actually need!

Rolling Back

There is no CLI command to “migrate down” a .net core project, but you can rollback manually. Inside each project directory you will find a backup folder with your original project.json file. You can pull this out and replace the csproj files with your project.json files again. Remember that after moving back to project.json, you will need to create/update your global.json file with the correct SDK versioning so it is able to be opened by Visual Studio 2015 again.

AWS Lambda is usually seen as a way for small, short functions to be run in the cloud. Usually small backend processes like resizing images or reading messages from a queue and processing them. But you can actually deploy an entire API on Lambda, and not only that, you can deploy an existing ASP.net Core API with very little extra effort.

It’s not always going to be the right architecture to be running a full API in Lambda, but if your API is being called infrequently and doesn’t need to be chewing resources 24/7, it might be a real cost saver.

Setup

If you haven’t done already, you need to install the AWS Tooling For Visual Studio 2017. Make sure VS2017 is closed while you install this. When opening Visual Studio again, you will see a window asking you to type in a few AWS credentials, follow the instructions to do so. This is mostly for deployment purposes from Visual Studio (Which this tutorial uses), but isn’t strictly required long term if you don’t want Visual Studio having access to your AWS account all the time.

For this tutorial, I’m creating a standard .net core API project in Visual Studio 2017 (The one that has the “valuescontroller” and nothing else). You can either create a new project to follow along or use your existing project, it’s up to you.

With your project open, you need to install the Amazon.Lambda.AspNetCoreServer nuget package. It’s currently in preview only at the moment so the command you need to run from your package manager console is the following :

One of the most frustrating bugs/issues in Visual Studio is that you can’t add CLI Tooling that lives in Nuget via the nuget package manager (See bugs like the following : https://github.com/aspnet/Scaffolding/issues/422). So you need to manually open up your csproj file of your project. In the ItemGroup for your Packages, add the following line :

And in your ItemGroup for DotNetCliTools add the following :

My complete csproj looks like the following if you get lost. This is just the standard .net core api project with the above nuget packages installed.

Code Changes

Add a class in your project named “LambdaFunction”, it should inherit from the abstract class “APIGatewayProxyFunction”. The code of this class should look like :

The biggest thing people ask when they hear about Lambda is “How can I test that locally?”.

Our LambdaFunction above is our entry point for AWSLambda, but you will notice that it’s pretty damn close to how our program.cs file looks in an ASP.net core project. When you run locally, our program.cs bootstraps Kestrel/IIS and starts hosting on our local machine. When you run in AWS Lambda, it doesn’t call Program.cs, it instead calls the code above and bootstraps everything for us, but the underlying code of controllers, services, pipelines etc are all the same. That means for the most part, the site locally and inside Lambda should function more or less identically.

Add a new JSON file to your project and name it “aws-lambda-tools-defaults.json”. This file holds a bunch of defaults when publishing from Visual Studio so you don’t have to type them over and over. Open up the file and enter the following :

The important thing to change here is the “function-handler”. The actual contents of this setting should be “{AssemblyName}::{LambdaFunctionName}::{FunctionHandler}”. In my case I named my project AWSApiExample, so you will need to swap this out for your project’s name. The “FunctionHandlerAsync” part is because our entrypoint that inherits from “APIGatewayProxyFunction” actually implements a methoid called “FunctionHandlerAsync” behind the scenes.

Another quick note is that I’m deploying this to the us-west-2 region, obviously change this if another region suits you better,

Deployment

Deployment could not be simpler! Right click your project and select “Publish To AWS Lambda”.

You should be given a screen to type in a few details, including naming your Function. Fill these out (Most should already be filled out), and be sure to tick the box that says it will save your settings. This actually just saves back to our json file from the last step, so you don’t have to pre-build that JSON file, but it’s much easier to copy and paste it in and just change the few details you need to. Click Next.

For permissions, if you have never used Lambda before (And don’t have a role for it), create a new role with the AWSLambdaFullAccess policy. Everything else on this page just leave default unless you know what you are doing!

Press upload and you should see your app be published up to AWS. Normally this would be the end of a normal lambda function publish, but now we need to setup our API Gateway. The API Gateway in Amazon simply acts as a proxy between the public and your Lambda. It can handle complex scenarios such as authorization, headers inspection etc, but we will actually be using it more or less as a straight pass through.

Open up your AWS Dashboard in your browser and head over to the API Gateway services screen. Go ahead and create a new API, name it whatever you like.

On the next screen, (Resources section of your new api), select the Actions dropdown and hit Create Resource. Here is where we basically create a wildcard pass through to our Lambda function. Tick the box that says “Configure as proxy resource” and leave everything else as is.

The next screen asks what you actually want to proxy to. Select Lambda Function Proxy, and select the region you deployed your Lambda function to. The most infuriating thing is that you have to type your function name here (Why can’t it just be a drop down!). Hopefully you remember what you deployed your function as (If not, in the AWS dashboard quickly pop over to the Lambda section and jog your memory).

Still in the Resources section. Select the Actions dropdown again and select “Deploy API”. A popup will come up, select new stage and type in “prod” as your stage name for now.

After hitting deploy, you will be given an “invoke” URL. I open my url and add on the end /api/values (Since I’m using the default .net Core API template). And what do you know!

So as we see, we can take an entire API and lift and shift it to Lambda. Again, I’m not really sure whether this makes total sense to do and I can’t see it being a hugely popular move, but it can be done (And fairly simple at that!).

In ASP.net core there is this concept of “environments” where you set at the machine level (Or sometimes at the code level) what “environment” you are in. Environments may include development, staging, production or actually any name you want. While you have access to this name via code, the main uses are actually to do configuration swaps at runtime. In full framework you might have previously used web.config transforms to transform the configuration at build time, ASP.net core instead determines it’s configuration at runtime.

It should be noted that there are two uses of the word “environment variables” being used here. The first is that “Environment Variables” are used to describe the actual definition of an environment variable on your machine. The second is that you can add an “environment” to that environment variables list to describe what ASP.net Core environment you are using… That may sound confusing but it will all come together at the end!

Setting Environment Variable In Visual Studio

When developing using Visual Studio, any debugging is done inside an IIS Express instance. You can set Environment variables for debugging by right clicking your project, selecting properties, and then selecting “Debug” on the left hand menu. By default you should see that a variable has been added for you called “ASPNETCORE_ENVIRONMENT” and it’s value should be Development.

You can set this to another value (like “Staging”), when you want to debug using another configuration set. It should be noted that editing this value actually edits your “launchSettings.json” and sets the variable in there. It ends up looking like this :

Setting Environment Variable Machine Wide

You will need to set the ASP.net core environment machine wide if…

  • You are not using Visual Studio/IIS Express
  • You are running the website locally but using full IIS
  • You are running the website on a remote machine for staging/production

To set your entire machine to an environment you should do the following :

For Windows in a Powershell window

For Mac/Linux edit your .bashrc or .bash_profile file and add

It should be noted that setting this up machine wide means that your entire machine (And every project within it) is going to run using that environment variable. This is extremely important if you are currently running multiple websites on a single box for QA/Staging purposes and these each have their own configurations. Setting the environment machine wide may cause issues because each site will think they are in the same environment, if this is you, read the next section!

Setting Environment Variable via Code

You can go through mountains of official ASP.net core documentation and miss the fact that you can set the ASP.net Core Environment through code. For some reason it’s a little known feature that makes the use case of multiple websites with different environments live on the same machine.

In your ASP.net core site, you should have a program.cs. Opening this you will see that you have a WebHostBuilder object that gets built up. You can actually add a little known command called “UseEnvironment” like so :

Obviously as a constant string it’s probably not that helpful, but this is regular old C# code so how you find that string is up to you. You could load a text file for example and from there decide which environment to use. Any logic is possible!

Accessing Environment via Code

To access the environment in your code (Such as a controller), you just have to inject IHostingEnvironment into your controller. The interface is already setup by calling “AddMvc” in your ConfigureServices method so you don’t need to add the interface to your service collection manually.

Here is some example code that returns the environment I am currently in :

Swapping Config Based Off Environment

In your startup.cs there is a method called “Startup” that builds your configuration. By default it adds a json file called “appsettings.json” but it can be used to add a file called “appsettings.{environment}.json where environment is swapped out for the environment you are currently running in. The code looks like this :

Any settings in your base appsettings.json are overwritten using your environment specific file.

Configuration itself is a massive topic and Microsoft has already done an incredible job of it’s documentation so head over and read it here.

Naming Conventions Per Environment

Again, another little known “feature” of using environments is that naming conventions can be used to completely change how your application starts. By default, you should have a file called startup.cs that contains how your app is configured, how services are built etc. But you can actually create a file/class called “startup{environmentname}.cs” and it will be run instead of your default if it matches the environment name your app is currently running in.

Alternatively, if you stick with a single startup.cs file, the methods Configure and ConfigureServices can be changed to Configure{EnvironmentName} and ConfigureServices{EnvironmentName} to write completely different pipelines or services. It’s not going to be that handy on larger projects because it doesn’t call both the default and the environment specific methods, it only calls one which could lead to a lot of copy and pasting. But it’s handy to know!

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