I can’t think to the last ASP.net project I worked on that didn’t involve Automapper in one way or another. In some ways, it’s become a bit like JSON.net where it’s just a defacto package to install when you start a new project. Automapper has, over time, been moving away from it’s static class origins into a more dependency injection type interface. This of course then lends itself perfectly for ASP.net Core’s new Service Collection framework!

This post will go over getting things up and running in ASP.net Core, but it does presume you already have quite a bit of knowledge about Automapper already. Let’s jump right in!

Setup

Inside your project, install the following Nuget package from the Package Manager console :

This will also in turn install the Automapper nuget package if you don’t have it already.

Inside your ConfigureServices method of your startup.cs, add a call to add the AutoMapper required services like so :

If you want to see what this call does, the actual code is open source and available here. In short, it trawls through your code finding all configuration profiles (See below), and registers the IMapper interface to be used in your classes. It is also rather particular about which scopes it will register them under – which we will also talk about shortly.

Adding Profiles

Automapper Profiles haven’t changed when you move to .NET Core. Take the example profile below where I have created a class called “DomainProfile” to add mappings, and inside the constructor setup a mapping.

When your application runs, Automapper will go through your code looking for classes that inherit from “Profile”, and will load their configuration. Simple!

Using IMapper

Once you’ve loaded up your profiles, using the IMapper interface is exactly the same if you used Automapper with any other DI Framework. You inject in IMapper to your constructor of your class, and are then able to map objects.

Again, it may look like a bit of black magic since you never registered IMapper in the ServiceCollection. But the Nuget package and the call to “AddAutoMapper” in your ConfigureServices takes care of all of this for you.

Scopes

One final thing to end on is how scopes work inside Automapper. Great care has been given so that you can write custom resolvers that rely on things like repositories that may be of transient scope. Confused? Let’s break it down a bit more.

Your configuration (e.g. Automapper Profiles) are singletons. That is, they are only ever loaded once when your project runs. This makes sense since your configurations will not change while the application is running.

The IMapper interface itself is “scoped”. In ASP.net terms, it means that for every individual request, a new IMapper is created but then shared across the entire app for that whole request. So if you use IMapper inside a controller and inside a service for a single request, they will be using the same IMapper instance.

But what is really important, is that anything that derives from IValueResolver, ITypeConverter or IMemberValueResolver will be of transient scope. They will also be created using the .NET Core Service Collection DI. Take the following code that may be used to resolve a particular mapping whereby I want to map across a username based on the source models “Id”. To do this I want to access my UserRepository.

Because this is instantiated as a transient instance using .NET Core’s Service Collection, my repository will also be resolved correctly and I will be able to do mappings that are more than just mapping across simple values. Super handy!

Have I missed anything? Drop a comment below and let me know!

In a previous post, I talked about getting Cookie Authentication up and running in ASP.net Core 1.X. In ASP.net Core 2.0, there has been a couple of changes to the API that are pretty easy to trip up on. Most of the changes are just a simple naming difference, but it can be pretty infuriating following a tutorial where one word trips you up! So let’s go!

Firstly, remember that this tutorial is for adding authentication to your app when you don’t want to use the out of the box “identity” services provided by ASP.net Core. It’s a very simple way to provide authentication cookies based on any logic you want, with any backing database you want.

Setup

If you are creating a new project, ensure that the “Authentication Type” when creating the project in Visual Studio is set to No Authentication. The other authentication types you can pick revolve around the inbuilt identity service, but since we are looking to do something more custom we don’t want this.

With your project up and going. In your nuget package manager, install the following package :

In the configure method of your startup.cs. Add the following line. Note that it should always come above your call to “UseMVC”, and likely above any other middleware calls that will return a result. Middleware runs in order, so you obviously want authentication to kick in before your MVC pipeline does!

In the ConfigureServices method of your startup.cs, you need to add the Cookie Authentication services with their configuration. It should look pretty similar to the following :

Where the Login Path is the URL to your login page. Remember this page should be excluded from authorization checks!

Disabling Automatic Challenge

Microsoft has decided that any time you access an endpoint that should be authorized, you should be redirected to the login page regardless. In ASP.net Core 1.X, this was not the case. You could set a flag called “AutomaticChallenge” to false. If you do not wish to always redirect the user (e.g. You would prefer to simply return a 401 response code – a Web API using shared Cookie Authentication is a good example where this would be relevant), you can override the redirect logic like so :

This overrides the redirect logic and instead returns a simple 401. There are other events you may wish to override at the same time (For example the UnAuthorized redirect etc).

Registering A User

In exactly the same manner as Cookie Authentication in ASP.net Core 1.X, registering a user will be entirely on you and will live outside any authentication code provided out of the box by Microsoft.

Logging In A User

For logging in a user, let’s create a quick model.

Now let’s create a controller called “Account” and create a POST method that accepts our login.

If you’ve followed our previous tutorial on Cookie Authentication in ASP.net Core 1.X, then this should look pretty familiar. And that’s because it’s the exact same code with one notable exception. This line here :

In ASP.net Core 1.X is actually

So that’s the only difference here.

Authorizing Controllers

This stays the same in ASP.net Core 2.0. You can simple add the “Authorize” attribute onto any controller or action.

Logging Our A User

Logging out a user stays fairly simple with one small change. The line to sign a user out inside an action is now

Previously in ASP.net Core 1.X it was :

With the release of .NET Core 2.0 comes a large “meta package” with the name Microsoft.AspNetCore.All. It’s a sort of god mode package that contains all you need to get up and running on ASP.net Core without having to figure out which nuget package does what. But it does have some massive pitfalls in my opinion.

Why Have A Meta Package At All?

When ASP.net Core is split into multiple smaller packages, the “versions” of these packages start to get all out of sync over time. This is especially true if you have ever tried to upgrade a project between .NET core versions, you end up having to go through all your smaller AspNetCore packages and work out which ones you should be version bumping. Take the following for example :

Here you have many aspnetcore and EntityFramework packages that all have slightly off versions. In ASP.net Core 2.0, using the “Microsoft.AspNetCore.All” meta package, your package references instead look like this :

What this should mean is that by updating a single package, you will be able to run on the latest ASP.net Core version. It also makes your csproj a bit easier on the eye with a single package being your “framework”, and any other package references being ones you have added explicitly.

What’s Inside The Microsoft.AspNetCore.All package

The meta package contains :

  • Every single AspNetCore package published by Microsoft
  • Every EntityFrameworkCore package published by Microsoft
  • Any supporting packages required for the framework to run (For example Json.Net)

Now, that probably sounds huge and you will probably ask yourself,  won’t the resulting deployment be out of control? You would essentially be “shipping” the entire framework right? Well..

Deployment and Runtime Store

Microsoft have gone back to something called the “Runtime Store“. I say the words “gone back” because this functions almost the same as the GAC on .net Full Framework projects. That is, your target machine would have to have the .NET Core runtime installed on it for you to be able to use the aspnetcore meta package. When you deploy, you won’t actually deploy any of the framework packages, your code will instead utilize the ones already on the machine.

And if the machine doesn’t have the runtime installed? Well, that’s where things start to fall down. If you are looking to do self contained deployments (Which was a massive selling point of .NET Core), then you cannot use the meta package. You would need to reference packages manually. I can see how this could turn into a headache down the road because it makes the creation of the project and whether you use the meta package so important. Imagine getting to the point you are ready to deploy, and your dev ops team prefers going down a self contained deployment route. Now you will have to go back and work out which packages you are using from the meta and add them all in manually. Painful!

Getting Started

By default, when you create any project using ASP.net Core 2.0, you will be using the meta package. If you know you won’t be using self contained deployments any time soon, then it’s safe to go ahead and use, and really, it does alleviate some headaches of knowing which packages have what. I can’t tell you how many times I start a new project and I have to go back and manually add in the packages for authentication, entityframework, staticfiles etc. Give it a go and let me know what you think below!

In a previous post, I wrote about how there was no way to send email on .NET Core. In version 1.0 of the framework and 1.6 of the standard, the SMTP client code in .NET was not yet ported over , that is until the release of .NET Core 2.0.

With things ported over, the interfaces and classes are virtually identical to ones you might have used in the full framework. Consider the following written in .NET Core 2.0.

For the most part, if you had code that could send email via SMTP in the full framework, it’s likely a matter of a copy and paste job to get it going in .NET Core now!

If you are having issues with this, ensure that you are on .NET Core 2.0 framework. You can check this by editing your csproj file, it should look like the following :

Where TargetFramework is set to 2.0. Anything lower and you will not have access to the SmtpClient class!

One of the easiest ways to publish your application to Azure App Service is straight from Visual Studio. While not an ideal solution long term or for any team over the size of one, it’s a great way for a solo developer to quickly get something up and running. Most of all, it doesn’t rely on any special configuration, scripts or external services.

Publish via Login

If the Azure account you are publishing to is the same one you use for your Visual Studio account or you have the username/password combination of the Azure account you are publishing to, you can publish direct from Visual Studio.

Inside solution explorer, right click your project and select “Publish”. You want to select “Azure App Service” on the next screen and “Select Existing”. The “Create New” option can be used if you don’t already have an App Service instance already (Rather than creating via the portal) – but we won’t do this this time around.

Click “Publish”. On the next screen you can select your Account, App Service and Deployment Slot to push to. Click “OK” and… that’s it. Really. You should see your project start building, publishing (via Web Deploy), and then Visual Studio will open your browser at the App Service URL.

Publish via Publish Profile

A publish profile is a settings file that holds all information for deploying your code direct to Visual Studio. The only real difference is that the publish profile can be given to you without you having any Azure login credentials yourself. Other than that, the actual deployment is largely the same.

To get a publish profile from the Azure Portal, head over to the dashboard of your App Service. Along the top you should see an option to “Get Publish Profile”.

With this file you are now able to deploy direct from Visual Studio. It’s important that this file is not just left lying around somewhere. With it, anyone can push code to your app service. So while it’s not quite the keys to the kingdom as much as a user/pass combination is, it’s pretty damn close.

Inside Solution Explorer, Right click your project, select Publish. Select “Import Profile” (You may have to scroll to the right to see this option).

Hit Publish! Immediately your project will build, publish and then open your browser at the App Service URL.

Obvious Issues

I touched on it earlier, but I feel the need to point it out further. Publishing from Visual Studio is not a long term strategy. Publishing from Visual Studio cuts out any CI/CD process you have running (If any), it creates possible inconsistencies with what you are deploying (Think “Did you get latest before you published?) and it creates a single point of failure of one developer doing all deployments in teams of more than 1.

That last point is important, while documentation can get some way around this, a single developer being the “release” guy usually creates some “magic” process where only that person can push code.

Again, with a single developer, especially when it’s just a hobby project, it’s less of an issue.

 

Deploying to the Azure App Service through Github is a simple but effective way to deploy websites that don’t require too much ceremony. Because many projects use Github for hosting their Git repositories, it’s a pretty seamless deployment process that is more around point and clicking in the Azure portal rather than having to write complicated deployment scripts.

It should be noted while this post references Github throughout, the exact same process can be used to setup Bitbucket to automatically deploy on a push.

Setting Up Github Deployment In Azure Portal

Setting up a Github Deployment for an Azure Web App Service is nothing more than a point and click process. Inside your App Service on the Azure Portal, select Deployment Options from under the Deployment category.

Select “Setup” on the online menu, and then select your source. In our case either Github or Bitbucket. You should now be able to click “Authorize” and use OAuth to connect your Github/Bitbucket account to Azure. Note that this account will be available for all other Azure App Services, not just this one.

Select your project and branch from the options. Typically your branch can just be master, but if this is a development instance you may want to use your develop branch, or you can even select a particular release branch if you are just using this deployment method as an easy way to push code rather than a continuous deployment strategy.

After connecting, wait 5 minutes for your project to sync up. Note that sometimes you need to go to a different blade in the portal and then head back to see updates (Not the greatest, but it works eventually!)

A great feature is that the deployment engine behind this will only sync files that are changed (Since it can see what has changed inside GIT). This makes deployments much faster than a FTP transfer or similar because it’s only uploading what it needs.

Any pushes to your selected branch will be deployed automatically within seconds, but if you get impatient, you can click the Sync button inside the Deployment Options blade and you should get a deployment going within seconds.

Rollback A Deployment

The Github CD Process allows you to roll back any deployment right from inside the Azure portal. Head to the Deployment Options screen inside your Azure App Service and select the deployment you wish to roll back to.

Select the option to “Redeploy” along the top menu and your previous deployment will be redeployed to production.

Linux App Service

If you are attempting to use Azure App Service with Linux (And now is a good time to be doing so, it’s 50% off!), unfortunately I couldn’t get Continuous Deployment working. Using the exact same Github repository but with a Linux App Service, the deployment failed. I have a sneaky suspicion that is related to the Docker Settings on App Service, but I wasn’t able to get things up and running. Feel free to drop a comment below if you have got it up and running!

With Azure App Service currently being 50% off for Linux, people are taking advantage and halving their .NET core hosting bill. And why wouldn’t you!? Because Azure App Service is fully PaaS, the underlying OS doesn’t make too much of a difference both from a deployment and management perspective.

Most deployment guides floating around the web center on deploying to a Windows App Service, which really isn’t too different to the Linux version, except for one important step. If you have deployed your ASP.net Core code and are not seeing anything when you visit your website in a browser, read on.

Docker Startup File

Linux App Service actually runs Docker under the hood. To get everything starting correctly you actually need to set a “startup file”. This is essentially the entry point for your app.

Inside the Azure Portal, inside your App Service, under the Settings category, find the option for “Docker Container”. Here is where you can set the runtime stack, but more importantly, your startup details.

For a dotnet project, the startup file line should read :  dotnet /home/site/wwwroot/{yourdllhere}

Where yourdllhere is the DLL of your main web project in your deployment. In practice it should end up looking a bit like this :

Once saved, you should head back to the app service dashboard and restart your service. It does take a while to boot up first time, so wait 5 minutes and give it a spin!

A quick and easy way to get your code up and running on Azure App Service is to upload your code using FTP. FTP can be as simple as a drag and drop process from your desktop, or as complicated as having your CI/CD pipeline run an FTP client for you. While it’s not an ideal scenario for large scale deployments due to the individual uploading of files one at a time, it’s a good starting point if you are just looking to have a play with Azure without too much fuss.

Setting Up FTP In Azure Portal

After creating your App Service, FTP may not be immediately available if you have never used it to deploy applications before. Deployment credentials, while they are viewable under a particular app service plan, are actually for the entire Azure account. So if you have *ever* used FTP or GIT to deploy apps before, the credentials will already be set and you should use those same ones. Resetting the credentials, even if you only do it within one app service, will reset them account wide.

Thankfully this is easy to check. Head over to your app service overview screen, if on this page you have an FTP deployment username showing, then you or someone else has already set up credentials.

If you don’t see anything here, then you will need to scroll down to the Deployment section, you should see an option for “Deployment credentials”.

Enter in a username/password combination you would like to use for FTP. Again, I cannot stress enough that this will be used on all FTP deployments for the entire account, not just this one app service plan.

Publishing Your ASP.net Core Web Project

Because App Service in Azure has a runtime installed, publishing your app is a one line job.

Open a command prompt in your project directory and run the following :

Heading to “bin\Release” you should see your published project for your .net core runtime (netcore1.0 or netcore1.1).

Uploading Your ASP.net Site

Back on your App Service overview, you should have a FTP hostname to connect to using your favourite client (I use Filezilla). After connecting, make your way to /site/wwwroot.

Upload your entire published app to the wwwroot.

Docker Settings For Linux App Services

Linux App Service plans are currently 50% of the Windows price right now, and given it’s a PaaS service, it really doesn’t make a huge difference what the underlying OS is. If you are using Linux, you will need one extra step to get going.

On the app service menu, under the Settings category, there should be an option for “Docker Container”. Here you can select your runtime stack but more importantly, you set the “entry” DLL for dotnet. Set the startup file to “dotnet /home/site/wwwroot/{yourdllhere}”.

Head back to the app service dashboard and restart the service. Wait 5 minutes and hit your URL and you should be up and running!

Route Constraints can be a handy way to distinguish between similar route names, and in some cases, pre-filter out “junk” requests from actually hitting your actions and taking up resources. A route constraint can be as simple as enforcing that an ID that you expect in a URL is an integer, or as complicated as regex matching on strings.

An important thing to remember is that route constraints are not a way to “validate” input. Any server side validation you wish to occur should still happen regardless of any route constraints set up. Importantly, know that if a route constraint is not met than a 404 is returned, rather than a 400 bad request you would typically expect to see from a validation failure.

Type Constraints

Type constraints are a simple way to ensure that a parameter can be cast to a certain value type. Consider the following code :

At first glance you might assume that if you called “/api/controller/abc” that the route would not match – It would make sense since the id parameter is an integer. But infact what happens is that the route is matched and the id is bound as 0. This is where route constraints come in. Consider the following :

Now if the id in the URL is not able to be cast to an integer, the route is not matched.

You can do this type of constraints with int, float, decimal, double, long, guid, bool and datetime.

Size Constraints

There are two types of “size” constraints you can use in routes. The first is to do with strings and means you can set a minimum length, max length or even a range.

This sets a minimum length for the string value. You can also use maxlength to limit the length.

Alternatively, you can set how many characters a string can be within a range using the length property.

While that’s great for string variables, for integers you can use the min/max/range constraints in a similar fashion.

Regex Constraints

Regex constraints are a great way to limit a string input. By now most should know exactly what regex is so there isn’t much point doing a deep dive on how to format your regex, just throw it in as a constraint and away it goes.

It is worth noting there for whatever reason, the .NET core team added another handy “quick” way of doing alpha characters only instead of regex. There you can just use the constraint of “alpha”.

 

Culture in ASP.net has always been a bit finicky to get right. In ASP.net core there is no exception but with the addition of middleware, things are now configured a little differently. Lifting and shifting your standard ASP.net code may not always work in ASP.net core, and at the very least, it won’t be done in the new “ASP.net Core way”.

It should be noted that there are two “cultures” in the .net eco system. The first is labelled just “Culture”. This handles things like date formatting, money, how decimals are displayed etc. There is a second culture called “UICulture” in .net, this usually handles full language translations using resource files. For the purpose of this article, we will just be handling the former. All examples will be given using datetime strings that will change if you are in the USA (MM-dd-yyyy) or anywhere else in the world (dd-MM-yyyy).

Setting A Default Request Culture

If you are just looking for a way to hardcode a particular culture for all requests, this is pretty easy to do.

In the ConfigureServices method of your startup.cs, you can set the DefaultRequestCulture property of the RequestLocalizationOptions object.

In the Configure method of your app, you also need to set up the middleware that actually sets the culture. This should be placed atleast before your UseMvc call, and likely as one of the very first middlewares in your pipeline if you intend to use Culture anywhere else in your app.

I can write a simple API action like so :

When calling this action I can see the date is output as MM-dd-yyyy (I am from NZ so this is not the usual output!)

Default Request Culture Providers

When you use the request localization out of the box it comes with a few “providers” that you (Or a user) can use to override the default culture you set. This can be handy if your app expects these, otherwise it can actually be a hindrance if you expect your application to be displayed in a certain locale only.

The default providers are :

QueryStringRequestCultureProvider
This provider allows you to pass a query string to override the culture like so http://localhost:5000/api/home?culture=en-nz

CookieRequestCultureProvider
If the user has a cookie named “.AspNetCore.Culture” and the contents is in the format of “c=en-nz|uic=en-nz”, then it will override the culture.

AcceptLanguageHeaderRequestCultureProvider
Your browser by default actually sends through a culture that it wishes to use. A browser typically sends through your native language, but it will throw in a couple of “options”. So for example my browser currently ends through “en-GB and “en-US” (Even though I am in NZ).

This header in particular can become very problematic. If the default culture of your *server* matches the culture that a browser sends. Then by default it doesn’t matter what you set the “DefaultRequestCulture” to, this will override it.

There are two ways to keep this from happening. The first is to tell ASP.net core that the only supported cultures are the one that you want the default to be. You can do this in the ConfigureServices method of your startup.cs.

The second way is to remove the CultureProviders from the pipeline all together.

The second method should be done in anycase if you don’t intend to use them as this makes your pipeline much cleaner. It will no longer be running a bunch of code that you actually have no use for.

Supported Cultures List

If you do intend to allow the user to set their own culture in their browser, you intend to use a query string to define the culture, or you intend to do a custom request culture provider (outlined in the next section) to allow code to set a custom culture based on other parameters, then you need to provide a list of supported cultures.

Supported cultures is a list of cultures that your web app will be able to run under. By default this is set to a the culture of the machine. Even if you use a custom culture provider as outlined below to set a culture, it actually won’t be set unless the culture is in the supported list.

You can set the list as follows :

So in this example, I have set the default localization to “en-US”. But if a user comes through with a cultureprovider that wants to set them to en-NZ, the code will allow this. If for example a user came through with a culture of “en-GB”, this would not be allowed and they would be forced to use “en-US”.

Custom Request Culture Providers

Going beyond hard coding a particular culture, often you will want to set culture based on a particular user’s settings. In a global application for example, you may have saved into a database what datetime format a user wants. In this scenario, you can use a custom RequestCultureProvider class.

The code looks something like the following :

Inside your ConfigureServices method in startup.cs, you then need to add your new CultureProvider to the RequestCultureProviders list. In the below example I have cleared out all other providers as I don’t care about query strings, cookies or the accept language header.

However let’s say that you do care, and if your custom provider can’t sort out a culture you want it to try query strings, cookies and the accept header. Then the best way is to insert it at the start of the list. Remember that these are run in order, the first provider that returns a culture instead of null wins.

Remember! It doesn’t matter what your custom culture provider returns if the culture it tries to set is not in the supported culture list. This is extremely important and the cause of many headaches!