Getting Started With ASP.NET Core 1.0 From Scratch
Jul 19, 2016
It’s an exciting time to be a developer. The tools available to us are getting better and more platform-agnostic and Microsoft is embracing the Open Source community. In this post, I am going to explore getting started with a ASP.NET Core app on Mac OS. I’m using Visual Studio Code as my editor but you can use whatever editor you prefer. Let’s get started!
First off, let’s create a directory and run dotnet new to create a new C# app. I’m calling my app HelloCore:
So, what just happened? Let’s take a look at project.json:
As you can see, by default it imports dnxcore50. Why? This allows us to reference pre-RC1 .NET Core Preview libraries. There is a lot of great info on Target Framework Monikers in this blog post. If you are unfamiliar with how .NET Core naming has changed, Hanselman does a really good job of explaining it here: ASP.NET 5 is dead - Introducing ASP.NET Core 1.0 and .NET Core 1.0 <- With a title like that, you basically don’t even need to READ the post.
In addition to project.json, we also have an entry point in to our application in Program.cs:
Next, let’s restore dependencies using dotnet restore:
And finally let’s run the app using dotnet run:
It’s nice that our app runs but it doesn’t actually do anything. Let’s add the following dependencies to our project.json file’s root-level dependencies property which was previously blank:
Do a dotnet restore to load in the new dependencies. For this app, I want to put my server-side code in a folder called Api and my client-side code in a folder called Client. So, first off: let’s create the Api folder and add a Startup.cs file with the following code:
Our app isn’t using this startup file yet or doing anything really. So, let’s change that by modifying our Program.cs file to configure and run our ASP.NET app:
We can’t currently run the app because the Client folder doesn’t exist so our file server doesn’t work. Let’s create the Client folder and add Index.html to it with the following content:
Note that this file references /Scripts/App.js which doesn’t exist yet. Before we create our script, let’s create a route that it can call to get some contact data. Create a Controllers folder under /Api/ and add ContactsController.cs with the following self-deprecating code:
Now that we have a api/contacts route, we can add App.js to /Client/Scripts/ (create the Scripts folder):
Now, if we do a dotnet run and navigate to http://localhost:5000/, we should be able to press our button and get data back from our API:
Conclusion
This is a very basic example but it will familiarize you with the building blocks of an ASP.NET Core web app. You can download/fork the source for this post here. As usual, let me know if you have any questions and I will be happy to help.