Edrick's Blog

ASP.NET Core - Create and Run with .NET CLI

October 06, 2019

Prerequisites

Getting Started

Create your source folder

mkdir Edrick.SampleApp
cd Edrick.SampleApp

The name of your source folder is used as a prefix in your solution and project files. The pattern that should be followed is : [Company].[Component].

Generate a solution file (.sln)

dotnet new sln
.
└── Edrick.SampleApp.sln

This generates a solution file with the same name as the current folder. The solution file is a structure for organising multiple projects. These projects can be a library, a test library, a web API or more.

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
MinimumVisualStudioVersion = 15.0.26124.0
Global
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal

The initial contents of the file look like this. Solution files do not generally need to be updated manually.

Generate a web API project

dotnet new webapi -o Edrick.SampleApp.Web
dotnet sln add Edrick.SampleApp.Web/Edrick.SampleApp.Web.csproj
.
├── Edrick.SampleApp.Web
│   ├── Controllers
│   │   └── WeatherForecastController.cs
│   ├── Edrick.SampleApp.Web.csproj
│   ├── Program.cs
│   ├── Properties
│   │   └── launchSettings.json
│   ├── Startup.cs
│   ├── WeatherForecast.cs
│   ├── appsettings.Development.json
│   └── appsettings.json
└── Edrick.SampleApp.sln

This generates the web API project in the folder Edrick.SampleApp.Web and adds it to the solution. The files generated include the project file Edrick.SampleApp.Web.csproj and files needed to start up a sample ASP.NET Core Project that returns the weather forecast.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
  </ItemGroup>

</Project>

Edrick.SampleApp.Web.csproj

Run the web API project

dotnet run -p Edrick.SampleApp.Web/Edrick.SampleApp.Web.csproj
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /Users/edrickleong/Documents/Edrick.SampleApp/Edrick.SampleApp.Web

This starts up the ASP.NET Core Web API Project at https://localhost:5001 with structured logging.

Executing a HTTP GET request on https://localhost:5001/weatherforecast returns a list of weather forecasts.


Edrick Leong

Currently living in Perth. Interested in software engineering, personal finance & rock climbing. Check out my Twitter here