ASP.NET Core 1.0 RC2 Environment Variables

This post has been updated to reflect Core 1.0 RC2 which was release mid may 2016.

Getting Started

A full list of environment variables can be founder here.
In RC 1, the environment variables  are set up in Properties > launchSettings.json.


What are Environment Variables?

“ASP.NET Core introduces improved support for controlling application behavior across multiple environments, such as development, staging, and production. Environment variables are used to indicate which environment the application is running in, allowing the app to be configured appropriately.” – from

In short, its common and easy to set up different environments such as:

  • Development
  • Staging
  • Production

And these “environments” have “environment variables” that can affect what your application does during run-time. Further more, you can build logic into your application, instructing it to perform different behaviors based upon its “environment”.


The ASPNETCORE_ENVIRONMENT (formerly known as ASPNET_ENV) variable defines what environment you are running in,  and if you have a startup class ending with this name then it will be call the configure method of that class instead of Startup.cs. e.g. StartupDEV if ASPNETCORE_ENVIRONMENT is equal to DEV


To reference your hosting environment in Startup.cs you will need to inject IHostingEnvironment. IHostingEnvironment is needed because it contains a property name “EnvironmentName”.  You can inject this into any method, but we want to inject it into the Startup() method.

public Startup(IHostingEnvironment env)
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
    if (env.IsEnvironment("Development"))
        builder.AddApplicationInsightsSettings(developerMode: true);
    else if (env.IsEnvironment("Staging"))
        //else if staging
        //else... do something cool
    Configuration = builder.Build().ReloadOnChanged("appsettings.json");

You can also reference them this way:


Here is a list from the blog listing examples of features you would only want in production.

  • Turn on caching
  • Ensure all client-side resources are bundled, minified, and potentially served from a CDN
  • Turn off diagnostic ErrorPages
  • Turn on friendly error pages
  • Enable production logging and monitoring (for example, Application Insights)

And here is an example of turning on  Application Insights only for production:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            app.UseMvc(routes =>
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

Setting your Environment Variable and launchSettings.json

There are a few ways to set your Environment Variables.  You can add the variable to your machine in your control panel under Advanced System Settings > Environment Variables (but you would have to do this to all of the places you run/test/develop) OR you can hard code some variable values in launchSetting.json for certain situations.

I prefer to do the latter for dev and staging.
The below example will set your ASPNETCORE_ENVIRONMENT to “Development” when running in Visual Studio, it will set it to “Staging” when published to a staging site. For production, if you have a system environment variable named ASPNETCORE_ENVIRONMENT (set to “Production”) wherever you host your production site, your app will then be set to “Production”.
Note: the variables them-self are case insensitive.

  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:XXXXX",
      "sslPort": XXXXX
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
    "web": {
      "commandName": "web",
      "environmentVariables": {

Entity Framework Core: Modeling and Connecting to SQL Views

This post is based on EF Core 1.0 and it will be strictly about adding SQL Views to your Model and Data Context.  If you are interested on how to connect your EF Core 1.0 project to a SQL Server DB then check out this other post about how to reverse engineer and scaffold your SQL Server DB.

The state of EF Core 1.0 and VS2015
Unfortunately, that nice UI you were used too that allowed you to connect and select the tables and views to be mapped out, does not yet exist.  After setting up your project and project.json file you will run a script in the Command Prompt or in the Nuget Package Manager to connect and build out you EF model.  Will look a lil something like this:

Command Prompt Scaffle Command

dotnet ef dbcontext scaffold "Server=SERVERNAME;Database=DATABASENAME;user id=USERNAME;password=USERPASSWORD;" Microsoft.EntityFrameworkCore.<wbr />SqlServer -o Models  --context MyDBDataContext --verbose

Nuget Package Manager Scaffle Command

Scaffold-DbContext "'Server=SERVERNAME;Database=DATABASENAME;Trusted_Connection=True;'" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

The above commands hook you up to your DB and creates a Model folder that contains all your newly generated classes and DataContext.cs.  But what about my views!?!?  Well, since your DataContext.cs is connected to your DB, you do technically have access to everything in that DB, including SPROCs and Views.  These Views just dont get created for you and there is no real way to access them except through inline SQL or manually adding them.  So lets manually add them together!

Create a new Class for your View

  1. Your project should have a Models folder (if you did everything here). Right click that Models folder and select Add > New Item.. > Class
  2. Name the Class “Team_View” and add this code to it.
    public class Team_View
    public int Team_ID { get; set; }
    public int? Players_Count { get; set; }
    public double? Total_Wins { get; set; }
    public double? Total_Losses { get; set; }

Add your new View’s Class to DataContext.cs

  1. In the Models folder, open up xxxxDataContext.cs. This file was automatically generated for you.
  2. In this class add this class object:
    public virtual DbSet<Team_View> Team_View { get; set; }
  3. In  OnModelCreating(ModelBuilder modelBuilder) add:
    modelBuilder.Entity<Team_View>(entity => { entity.HasKey(e => e.Team_ID); });
  4. Your DataContext should now look something like this
    public virtual DbSet<Team_View> Team_View { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    modelBuilder.Entity<Team_View>(entity => { entity.HasKey(e => e.Team_ID); });

Also, note that the DataContext is a “Shared” class.  So if you don’t want to re-write this code every time you run the update scaffold command, putting code like this Team_View code in a separate shared DataContext.cs file may be the way to go.

Thats It!
You now have access you your View! AND you now have a Class for that view! You can now call it from any lambda/LINQ  query that your want.

Entity Framework Core 1.0 -Lazy Loading and Eager Loading

EF Core 1.0 does not support automatic lazy loading and eager loading related objects in the same way that EF6 did. Lazy loading does make data access easier and it cuts the code you have to write to reach that data significantly,  so its good to see that it is still listed as a priority item here on EF’s  Roadmap.

Until then, the way to eager load related objects, is by the .Include() and .ThenInclude() methods.  Here are two examples.

var leagues = db.Leagues
            .Include(l => l.Teams)
            .ThenInclude(t => t.Players)
var leagues = from d in db.Leagues.Include(l => l.Teams) select d;

Creating your first AngularJS – ASP.NET Core 1.0 application

This post will work off a project I created in a previous post – Creating Your First ASP.NET Core 1.0 Application from Scratch – and it will get you set up with AngularJS, Grunt, and Bower.

Add an NPM Configuration File and install Grunt and Bower

1. Right click the project and select Add > New Item. Select NPM Configuration File and name it package.json

2. Open up package.json and add the following 4 dependencies

    "version": "1.0.0",
    "name": "ASP.NET",
    "private": true,
  "devDependencies": {
    "grunt": "0.4.5",
    "grunt-contrib-uglify": "0.11.0",
    "grunt-contrib-watch": "0.6.1",
    "bower": "1.7.2"

What did we just do?

In our package.json file, we’ve indicated that we need three NPM packages named grunt, grunt-contrib-uglify, and grunt-contrib-watch. After the name of each package, we’ve specified the version of the package that we need.  Grunt and Bower are now installed in our project!


Add a Grunt Configuration File

1. Right click the project and select Add > New Item. Select Grunt Configuration File and name it gruntfile.js

What is Grunt?

Grunt is an open-source tool that you can use to build all of the frontend resources for your project. For example, you can use Grunt to compile your Less or Sass files into CSS. You can also use Grunt to combine and minify CSS and JavaScript files.

2.  Open up gruntfile.js and load your plugins by adding the following.


3. Next add your configurations to the grunt file

    uglify: {
        my_target: {
            files: {
                'wwwroot/app.js': ['Scripts/app.js', 'Scripts/**/*.js']
    watch: {
        scripts: {
            files: ['Scripts/**/*.js'],
            tasks: ['uglify']
grunt.registerTask('default', ['uglify', 'watch']);

4. Your gruntfile.js should now look like this


What did we just do?

We told Grunt to look for a javascript file named app.js and then, on build, we want it to minify (uglify) the app.js file and put it into our wwwroot  (we will create the app.js file later in this tutorial).

Add JQuery and Bootstrap to our project using Bower

What is Bower?

Bower is a package manager created by Twitter that is designed to support front-end development. You can use Bower to manage resources such as AngularJS, jQuery, and Bootstrap.

1. Right click the project and select Add > New Item. Select Bower Configuration File and name it bower.json

2. Open up bower.json and add JQuery and Bootstrap to its dependencies

    "name": "ASP.NET",
    "private": true,
  "dependencies": {
    "jquery": "2.2.0",
    "bootstrap": "3.3.6"

3. Your bower.json file and projectfolder structure should now look like this:



Wow, now we have Nuget, NPM, and Bower package managers in our project.  Why do we need all of them and what do they do?  Check out my blog post about that here – Nuget vs NPM vs Bower.


Installing AngularJS

1. Open up bower.json and add these AngularJS modules to its dependencies. For this project we will just be using the “angular package”, but I wanted to show here that “angular-resource” and “angular-route” are added in the same way.

  "name": "ASP.NET",
  "private": true,
  "dependencies": {
    "jquery": "2.2.0",
    "bootstrap": "3.3.6",
    "angular": "1.4.8",
    "angular-resource": "1.4.8",
    "angular-route": "1.4.8"

2. Save and compile the project and you will see that the above modules were added to you wwwroot folder and your Bower folder.  Should look like this:



Add Scripts

1. Right click the project and select Add > New Folder.  Name it “Scripts”.

2. Right click the Scripts folder and select Add > New Item…  Select JavaScript File and name is app.js

3.  This is the same app.js file that we look for in our gruntfile.js code a few steps above.  The next thing we will do is initialize the angular application.  To do this, add the following to app.js

var app = angular.module("myApp", []);

4. To have Grunt uglify app.js and add it to our wwwroot folter, do the following. Open up Visual Studio’s Task Runner Explorer (View > Other Windows > Task Runner Explorer)

5. Refresh the Task Runner Explorer.  You should see your Gruntfile.js there.  Drill down into Alias Tasks. Right click and run default.  This will minify (uglify) your app.js file and add it to your wwwroot.


Use static files

1. You want to tell your app to use static files like app.js and the other angular and bootstrap files. To do this open up Startup.cs and add this to the Configure(IApplicationBuilder app) method.


2. The method Configure(IApplicationBuilder app) should now look like this:


Writing some AngularJS!

1. Open up Views/Home/Index.cshtml

2. Replace what is in Index.cshtml with the following

<!DOCTYPE html>
<html ng-app="myApp">
    <meta name="viewport" content="width =device-width" />
    <title>AngularJS and ASP.NET 5 Example</title>
    @*add styles here*@
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <h2>Hello Home Index Page</h2>
    Name : <input type="text" ng-model="name">
    Hello {{name}}
    @*add javascript files here*@
    <script src="~/lib/angular/angular.js"></script>
    <script src="~/app.js"></script>

What did we just do?

In the above html we are loading Bootstrap, JQuery, AngularJS, and app.js.  We are then adding ng-app=”myApp” to the HTML tag. The ng-app directive defines an AngularJS application and its module is created in app.js.  If these angular terms are unfamiliar to you, please check out for a more detailed explanation of the Angular code seen here.


You now have a working ASP.NET Core 1 AngularJS Application.

Check it out on GitHub