User Tools

Site Tools


net_core_in_linux

.NET Core in Linux

Installation of .NET Core

These instructions are for .NET Core v1.0.4 in Linux Mint 18. Instructions for other versions and other distros are very similar.

Please visit https://www.microsoft.com/net/core for more information.

Add the apt-get feed for Linux Mint 18:

sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main" > /etc/apt/sources.list.d/dotnetdev.list'
 
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893
 
sudo apt-get update

Install the .NET Core SDK:

sudo apt-get install dotnet-dev-1.0.4

If you'd like to install a different version, ensure that you're installing the latest version, or just check to see what's available, you can search with apt-cache:

apt-cache search dotnet

Create a test app:

dotnet new console -o testinstallation
 
cd testinstallation

Restore the app's required packages, and run it:

dotnet restore
 
dotnet run

When you see “Hello, World!” as your output, you've verified your installation, and .NET Core is ready to go!

Visual Studio Code

There's no “Visual Studio IDE Community Edition” for Linux yet, but Microsoft has created a very capable cross-platform programmer's editor called Visual Studio Code. It includes many of the handy features and behaviors you've grown used to in the Visual Studio IDE.

  1. Click the Visual Studio Code download button.
  2. Click the .deb button.
  3. After the download completes, click the .deb file. It will launch Package Installer automatically.
  4. Click the “Install Package” button.

After the installation completes, locate Visual Studio Code in your menu and launch it.

Before you start working on any projects, you'll need to install the C# extension:

  1. Locate the Extensions button in the sidebar and click it.
  2. In the search box, type C#. It will probably be the first match. Verify by looking for the description “C# for Visual Studio Code (powered by OmniSharp)”.
  3. Click the Install button.
  4. After the install completes, you'll be prompted with a Reload button. Go ahead and click it. The extension will be activated.

Visual Studio Code has a very active extension community. I recommend searching the extension marketplace. You'll find lots of useful items.

One example: You'll probably want to install the “C# Extensions” extension, by jchannon. It simplifies the creation of C# classes and interfaces.

Now you're ready to create some projects!

.NET Core Project Examples

The .NET Core CLI provides several project templates. This command:

dotnet new

…will show you a list, something like this:

Templates                 Short Name      Language      Tags
----------------------------------------------------------------------
Console Application       console         [C#], F#      Common/Console
Class library             classlib        [C#], F#      Common/Library
Unit Test Project         mstest          [C#], F#      Test/MSTest
xUnit Test Project        xunit           [C#], F#      Test/xUnit
ASP.NET Core Empty        web             [C#]          Web/Empty
ASP.NET Core Web App      mvc             [C#], F#      Web/MVC
ASP.NET Core Web API      webapi          [C#]          Web/WebAPI
Solution File             sln                           Solution

The calling convention to create a project is as follows:

dotnet new <template short name> -o <project name>

The -o argument is optional, but I recommend using it, since it also controls the naming of the files in the project folder, along with creating the folder itself.

Let's step through the creation of the console, mvc, and webapi project types.

Console Application

A console project is the simplest, and is nice for finding your way around. We'll create a console project called “Hello”, and restore its required packages:

dotnet new console -o Hello
 
cd Hello
 
dotnet restore
  1. After you create the project, open Visual Studio Code.
  2. On the Welcome page, you'll see an “Open folder…” link. Click it, and open the Hello project folder.
  3. In the Explorer panel, click Program.cs.
  4. You'll see a prompt indicating that required assets to build and debug are missing, asking if you'd like to add them. Click “Yes”.

At this point, you have a runnable project. Press [F5]. The project will build and run, and you'll see “Hello World!” in your Debug console.

Now you can make any changes you require. As a simple exercise, we'll create a Greeter class to handle our “Hello World” duties. :-)

  1. In the sidebar, click Explorer, to show the file list.
  2. In any empty space, right-click and select “New file”.
  3. Name the file “Greeter.cs”.
  4. Create a basic class, with a hello method, as follows:
using System;
 
namespace Hello
{
    public class Greeter
    {
        public void SayHello()
        {
            Console.WriteLine("Hello, world!");
        }
    }
}
  1. Click “Program.cs” in the Explorer panel.
  2. Replace the Console.WriteLine(“Hello World!”); line with this:
Greeter myGreeter = new Greeter();
myGreeter.SayHello();

Press [F5], and you should see “Hello, world!” in the Debug console.

You've now generated a console app, and enhanced it with a simple class!

ASP.NET Core Web App (MVC)

Now we'll move from a text-based console client to the web.

Generate a MVC web application project:

dotnet new mvc -o SimpleMVC
 
cd SimpleMVC
 
dotnet restore
  1. Open Visual Studio Code, then open the new MVC project by clicking “Open folder…” and selecting the SimpleMVC folder.
  2. Click Startup.cs, and add the required assets when prompted.

The project should now be runnable. Press [F5], and the project will build and run. It should launch in your default web browser as localhost on port 5000. You will see a simple application with “Home”, “About”, and “Contact” pages. After you've clicked each page and verified that they load properly, close the browser tab and stop the running project by clicking the “Stop” button in Visual Studio Code.

Let's add a new page called “Company”:

  1. In the Explorer panel, right-click on the “Home” folder (under “Views”), and select “New File”.
  2. Name the file “Company.cshtml”.

Add the following HTML to Company.cshtml:

@{
    ViewData["Title"] = "Company";
}
 
<h2>Company Name</h2>
<p>Company info will go here</p>

Open HomeController.cs and add an action result for the new page:

public IActionResult Company()
{
  return View();
}

Open _Layout.cshtml (in Views/Shared) and add a menu entry for the new page in the “nav navbar-nav” section:

<li><a asp-area="" asp-controller="Home" asp-action="Company">Company</a></li>

Press [F5] to compile and run. You should see a new entry for “Company” in the menu. Clicking it should load the new page.

Postman

Before moving on to creating a web service, you'll need a way to test your service. I recommend Postman. You can download it here.

  1. Choose the Linux download, 64 or 32-bit.
  2. The Postman archive will download automatically.
  3. Extract it wherever you like.
  4. Click “Postman” in the extracted folder to run it.

For local testing of services, it's as simple as this:

  1. Select the request type. (GET, POST, PUT, etc.)
  2. Copy the request URL to the “Enter request URL” field.
  3. Click “Send”.

Postman also supports various authentication types, sending complex requests, additional headers, etc, but we won't need these features for the service we're creating.

ASP.NET Core Web API

For our final project, we'll create a simple RESTful web service.

Generate a Web API project:

dotnet new webapi -o SimpleService
 
cd SimpleService
 
dotnet restore
  1. Open Visual Studio Code, then open the new Web API project by clicking “Open folder…” and selecting the SimpleService folder.
  2. Click Startup.cs (in the Explorer tab), and add the required assets when prompted.

Open the ValuesController.cs file (in the Controllers folder) and you'll see that the template has already generated some endpoints for you. Let's test the api/values endpoint:

  1. Press [F5]. The project will compile and run, launching your default web browser.
  2. The browser will report that it is unable to load localhost:5000. That's OK! (The root path is not a valid endpoint.)
  3. Leave the project running, and load Postman.
  4. Make sure you have “GET” selected as your request type.
  5. Enter the following URL into the Postman “Enter request URL” field: http://localhost:5000/api/values
  6. Click “Send”.

You should see this returned in Postman:

[
  "value1",
  "value2"
]

If you look at the matching code in ValuesController.cs:

// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
  return new string[] { "value1", "value2" };
}

…you can see that this is what it's supposed to be returning.

Visual Studio Code also has integrated debugging.

  1. Add a breakpoint on the “return new string…” line by clicking just to the left of the line number.
  2. Switch back to Postman and click “Send” again. Execution of the service will pause on the line with the breakpoint.
  3. Continue by pressing [F5].

Now, stop the service by clicking the “Stop” button in Visual Studio Code, and we'll add our own controller. We'll add a very simple “Get” endpoint that takes a number and returns the square root of that number.

  1. Right-click on the Controllers folder and select “Add file”.
  2. Name it “MathController.cs”.
  3. Add the following code to MathController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
 
namespace SimpleService.Controllers
{
    [Route("api/[controller]")]
    public class MathController : Controller
    {
        // GET api/math/5
        [HttpGet("{id}")]
        public string Get(double id)
        {
            return Math.Sqrt(id).ToString();
        }
    }
}
  1. In Postman, change your request URL to this: http://localhost:5000/api/math/25
  2. Click “Send”.

You should see a “5” returned.

Now, let's take it one step further, and add a Model to do our math work for us.

  1. Stop the service, if it's still running.
  2. Right-click on an empty space in the Explorer pane, and select “New folder”. Name it “Models”.
  3. Right-click on Models and select “New file”. Name it MathProvider.cs.
  4. Add the following code to MathProvider.cs:
using System;
 
namespace SimpleService.Models
{
    public class MathProvider
    {
        public double GetSquareRoot(double inputValue)
        {
            return Math.Sqrt(inputValue);
        }
    }
}
  1. Switch to MathController.cs.
  2. Add a using statement to make our new Models class accessible to the controller:
using SimpleService.Models;

Change the Get method as follows:

public string Get(double id)
{
  MathProvider myMath = new MathProvider();
 
  return myMath.GetSquareRoot(id).ToString();
}
  1. Click [F5] to run the service.
  2. In Postman, click “Send”.

You will see a “5” returned again, but now it will be returned from our new model. (If you'd like, set a breakpoint in the GetSquareRoot method of the MathProvider class to confirm that it's being hit.)

Congratulations, you've created a Web API service and added your own endpoint, along with a new model!

Installing Nuget Packages

To add nuget packages to an existing project, open a terminal in the root folder of the project, then issue a dotnet command in the following format:

dotnet add <PROJECT> package [arguments] [options]

For example, to add the Microsoft.AspNetCore.StaticFiles package, you'd do this:

dotnet add package Microsoft.AspNetCore.StaticFiles

If you want to add a specific version of a package, use the -v argument, like this:

dotnet add package Microsoft.AspNetCore.StaticFiles -v 1.0.1
net_core_in_linux.txt · Last modified: 2023/07/14 12:59 by jimc