HttpContext has had a bit of a shifting around in ASP.net core. While everyone has their own ideas on best practices, it’s a bit of a consensus that the usage of calling “HttpContext.Current” outside the scope of a controller (For example in a service class) was getting out of hand. It also made testing just that little bit harder.

So how to do it now? There are two ways.

Inside Controllers

Inside a controller, you can still access HttpContext by doing the following :

No, there is nothing special that I have done to access the Property “HttpContext”, it’s just available when inheriting from the base “Controller” class. Simple!

Inside Services

Inside services is a little tricker, but still possible. Note that you may want further abstraction away from directly accessing an HTTPContext, for example if you are using it for “Sessions” you may want to abstract it away incase you scale your servers horizontally and you will no longer be able to use the HTTP Session object within C#. But if you don’t think you’ll need that, read on!

First in your startup.cs, you need to register IHttpContextAccessor as a service like so :

In earlier versions of .net Core, IHttpContextAccessor was automatically registered. This was removed and announced here. So you need to register it manually if you intend to use this inside services.

When you create a helper/service class, you can then inject in the IHttpContextAccessor and use it. It would look like something not too dissimilar to this :

Unfortunately if you have accessed HttpContext throughout your old .net 4.5 code and are looking to upgrade to .net Core, you will have to do a bit of work to get it working again. But it’s worth it for the nice clean approach to DI and better testability.

By default, browsers abide by the Same-Origin policy, which is that documents (Or in most cases scripts) cannot interact with a resource from another domain. It isolates, for example, a malicious script being able to do “too much”. A script loaded from a third party should not be able to call your own API. However in some cases this actually may be warranted.

Enter CORS

CORS or Cross-Origin Resource Sharing is a way to by-pass this limitation/security measure for legitimate reasons. The most common in the context of ASP.net core is that you are building a Single Page Application, and you wish to host your API on another domain. For example your website is www.mywebsite.com and your API is api.mywebsite.com. Any scripts be they from jQuery, Angular, React, Backbone, whatever cannot make HTTP calls from www.mywebsite.com to api.mywebsite.com.

Configuring CORS In ASP.net Core

Let’s get going and see how this works in ASP.net Core

First you need to add the Microsoft Cors package from Nuget.

You then need to add the CORS services. In your startup.cs in your ConfigureServices method you should have something similar to the following :

Next you need to add the CORS middleware to your app. In your startup.cs you should have a Configure method. You need to have it similar to this :

The options lambda is a fluent API so you can add/remove any extras you need. You can actually use the option “AllowAnyOrigin” to accept any domain, but I highly recommend you do not do this as it opens up cross origin calls from anyone. You can also limit cross origin calls to their HTTP Method (GET/PUT/POST etc) so you can only expose GET calls cross domain etc.

Important!

Two very important points.

  • Incase it wasn’t obvious, the above is to be done on your API not your web project!
  • Your protocol is important. http://www.mydomain.com is not the same as https://www.mydomain.com

It’s not like the war of Pascalcase vs Camelcase hasn’t been going on for a very long time, but in ASP.net core it flared up again with a breaking change in ASP.net core 1.0. You can read the actual change request here on Github, and then the subsequent announcement with some unhappy campers here.

To be clear.

In earlier versions of Web API and indeed early versions of ASP.net core, the default serialization of an object to JSON results in Pascalcase names. When a C# app is talking to another C# app, the casing actually doesn’t matter. You can send JSON data with mYVaRiAbLE and it will still be deserialized into MyVariable in C#.

The issue usually reared it’s head when you were using javascript to consume your Web API. Afterall, when Mozilla, Google, jQuery, WordPress and countless others cite camelCase as the standard for Javascript naming, it’s probably what most people expect to see. If you are binding a model using Angular or similar from a Web API, you probably want to keep with the same naming format. Not have properties that came from your API suddenly be in Pascal Case.

It mostly comes down to the 80/20 rule. I would say a large majority of people using ASP.net core are also using some sort of javascript framework to bind models. And for that, camelCase is best.

So, what are your options if you are still #TeamPascalCase?

Change To PascalCase In ASP.net Core 1.0+

Probably the most annoying thing about this change is that you need to change the ContractResolver for the Json Serializer. The thing that gets people’s goat is that the resolver that makes things PascalCase is actually called the “DefaultContractResolver”…. Even though in version 1.0 and onwards it isn’t the default at all…..

In anycase, in your startup.cs file, find your ConfigureServices method. You should already have an AddMVC call, and tack onto it like so :

Change To camelCase In ASP.net Core <1.0

Just incase you are behind with the times in ASP.net Core versions and you want to move to camelCase by default (Possibly in preparation for upgrading), you can do so by doing similar to the above, but instead making the contract resolver camel case like so :

In a previous article we went over how to read custom configurations into memory in ASP.net core. This is also the new way to do Appsettings. But did you know that you can also do “hot loading” of configurations? That is, while your app is running, you can change an appsetting or configuration and your application will reload it on the fly without an app pool recycle or restarting the web server? Pretty nifty! Let’s take a look.

A couple of notes before we start :

  • We will be reusing our code from the custom configurations in asp.net core tutorial. If you haven’t read that yet maybe take a quick read to make sure we are on the same page.
  • This only works in ASP.net core 1.1 and up. Before that there were a couple of hot loading options that made it into early versions but ended up being problamatic and being removed. In earlier versions this was named IOptionsMonitor (Which is still there under the hood).

First, in your Startup.cs ensure that when you load your appSettings.json, that reloadOnChange is set to true. It should look something like this :

When you load your configuration into your services collection, you now must load it as configuration as opposed to loading it as a POCO. That means it should look like this :

When you request it into your controller/service, you then need to use IOptionsSnapshot rather than IOptions.

And that’s all! Now whenever you change configuration, your configuration is reloaded and your changes are seen instantly without a large restart required. This would be handy if you were deploying a prototype or a new feature that you’re unsure of how it would perform and need a way to tune it or disable the feature all together without requiring wholesale restarts.

Important. It’s A Snapshot!

It should be noted that the name IOptionsSnapshot is as the name implies, it’s a snapshot. If you for example take the value and hold onto that for some reason (In your own cache for example), these will not be hot loaded when changing configuration. Instead each time IOptionsSnapshot is injected into a class it will be given it’s unique value. This is very important to remember. Consider the following code :

Where the configuration value of MyProperty is a boolean. If between the first and second calls to the value of MyProperty, I go into the configuration and change the value. What do you think this action will return? The answer is true as IOptionsSnapshot only reads the configuration when being created, not when you request the value from it.

In our example here, we are using an MVC controller which is Transient scope. Meaning that each time we request the controller, our DI recreates it for us. But it’s important to remember that if you are using something with a Singleton scope (Or to some extent a “scoped” scope), and injecting IOptionsSnapshot into that, the options will never be updated.

Frustratingly .net Core early releases were without URL Encode and Decode methods. Whereas previously you were able to access the HTTPUtility namespace for encoding and decoding strings, this was not ported to .net core.

Until now!

Microsoft has moved the UrlEncode and Decode methods into a WebUtility static class. If you are super nosy you can see the code that’s doing your encoding here.

To get access you need to install this nuget package, which at the time of writing means running this command from your package command line :

Now you have access to URL Encoding

Custom Model Binders are a super helpful tool in “binding” a view model in unconventinal ways. There are a few reasons you may find yourself using a custom model binder.

  1. You are taking in values in seperated out fields, but want to combine them into a single object/struct.
  2. The model the front end is sending is actually nothing like the backend model, and neither side can change for some reason. (We’ve all been there!)
  3. You need to “Supplement” your model with outside data that isn’t coming in the payload (e.g. a cookie, a value from a database/config etc).

We will be focussing on the first reason as it’s the easiest to demonstrate. However once you have the hang of a custom model binder the possibilities really open up and there is no limit to what you can bind.

In our example, we are requesting a URL like the following :

http://www.mydomain.com/date?day=1&month=2&year=1985

This might happen if you have separated out select boxes for your dates for whatever reason. You end up with each portion of the date coming through individually. On the backend this can be a pain because we want to deal with a single Datetime object. We could receive all of these individually and build them up in the action, or we could “bind” them before it even reaches the action. Let’s see how.

First, we build our ViewModel of what we want to receive. In our case it’s a simple class with a single property :

Next we build a “ModelBinder” that inherits from IModelBinder. This might look like the following :

Notice that in this case we reach into the query string to read our values, but this could be from anywhere.

In the latest version of ASP.net core, we also need to use a provider. A provider tells ASP.net core when to use our custom binder. For us it’s very simple. If the model we are binding to is of type “MyViewModel” then use our binder. Of course this can be much more complicated and can even return different binders based on code within the provider. Our provider looks like the following :

Simple!

Next we just need to let ASP.net Core know that we have a model binder ready for use. You do this in your startup.cs file in the ConfigureServices method :

Finally, create your action in your controller that asks for “MyViewModel”. Something like the following :

And all going well, when you call your URL you should see :

As you can see, Model Binding really isn’t that hard. It may seem a bit overkill at first, but simply knowing it exists means that when that one time you actually need it comes up, you have it ready to use at your disposal.

If you’ve been using ASP.net for any length of time you’ve probably had to build your own implementation of the CustomConfiguration class or had to implement the IConfigurationSectionHandler. This usually included writing out each configuration element and how to read it from the XML (Including conversions/casts). What a pain!

DotNetCore takes a much simpler approach to custom configurations. There are two main ways to use it, one that uses an Options class from .net Core, and one that uses simple POCOs.

Method 1 : The Options Class

This way is the most common example you’ll see out there. It uses the Options class built into .net core and is pretty easy to get going. Because it drags around the “options” class, it actually isn’t my preferred method. I much prefer simple POCO’s. If you do too, then skip to Option 2 below. Otherwise read on!

Imagine you have an appSettings.json like so :

You would create a simple configuration class like the following in your project :

Notice how in the above we don’t have to inherit or implement any interfaces/classes. It’s a simple POCO that doesn’t require any additional references.

Now in your startup.cs, you have the following :

Notice in the ConfigureServices method we add a configuration to our services. This is all it takes

Next we go to any controller and we can reference IOptions<MyConfiguration> to access our custom configuration.

Simple right? But from the above you can probably pick why this isn’t my preferred method. We drag along this IOptions interface but pull the value from it immediately. If we could inject our POCO class that holds our configuration then we don’t need to drag around the IOptions interface. Let’s take a look at that.

Method 2 : Get Configuration Poco

Utilizing what we already have above, we just need to change a couple of lines. In our startup.cs we need to change the call to configure to one that just binds a POCO :

A couple of notes :

  • You previously were able to call “AddInstance” on an IServiceCollection. This was removed to just allow “AddSingleton”, which really is one and the same anyway.
  • Previous versions of .net Core (Pre 1.1) did not allow a call to “Get”, instead you had to do a call to “bind”. This was an added annoyance as you had to instantiate an empty class first. If you are on an early version and unable to upgrade, do the below.

Bind option (Pre ASP.net core 1.1) :

Then if you go to your class, you only need to ask for your POCO, not the IOptions. Like so :

Best Practice

If you go with Method 2. A good habit to get into is to always inject in an interface instead of your concrete class. This allows for easier mocking when doing unit testing, and it better follows the Dependency Inversion principle which is that you depend on abstractions.