Getting Started with ASP.NET Core

Visual Studio for Mac makes it easy to develop your app's service with its support for the latest ASP.NET Core Web development platform. ASP.NET Core runs on .NET Core, the latest evolution of the .NET Framework and runtime. It's been tuned for fast performance, factored for small install sizes, and re-imagined to run on Linux and macOS, as well as Windows.

Installing .NET Core

.NET Core 1.1 is automatically installed when you install Visual Studio for Mac.

Creating an ASP.NET Core app in Visual Studio for Mac

Open Visual Studio for Mac. On the welcome page select New Project...

New Project Dialog

This will display the New Project dialog, allowing you to select a template to create your application.

There are a number of projects that will provide you with a pre-built template to start building your ASP.NET Core Application. These are:

  • .NET Core > ASP.NET Core Empty Web Application
  • .NET Core > ASP.NET Core Web App
  • .NET Core > ASP.NET Core Web API
  • Multi-platform > App > Connected App

ASP.NET Project Options

Select the ASP.NET Core Empty Web Application and press Next. Give the Project a Name and press Create. This creates a new ASP.NET Core app, that should look similar to the image below:

New ASP.NET Core Empty Project view

The ASP.NET Core Empty Web Application creates a web application with two default files: Program.cs and Startup.cs, which are explained below. It also creates a Dependencies folder, which contains your project's NuGet package dependencies such as ASP.NET Core, the .NET Core framework, and the MSBuild targets that build the project:

Solution Pad displaying dependencies

Program.cs

Open and inspect the Program.cs file in your project. Notice that two things are happening in the Main method – the entry into your app:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

An ASP.NET Core app creates a web server in its main method by configuring and launching a host via an instance of WebHostBuilder. This builder provides methods to allow the host to be configured. In the template app the following configurations are used:

  • UseKestrel: Specifies the Kestrel server will be used by the app

  • UseContentRoot(Directory.GetCurrentDirectory()): Uses the web project's root folder as the app's content root when the app is started from this folder

  • .UseIISIntegration(): Specifies that the app should work with IIS. To use IIS with ASP.NET Core both UseKestrel and UseIISIntegration need to be specified.

  • .UseStartup<Startup>(): Specifies the Startup class.

    The Build and Run methods build the IWebHost that will host the app and start it listening for incoming HTTP requests.

Startup.cs

The Startup class for your app is specified in the UseStartup() method on the WebHostBuilder. It is in this class that you will specify the request handling pipeline, and where you configure any services.

Open and inspect the Startup.cs file in your project:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

This Startup class must always adhere to the following rules:

  • It must always be public
  • It must contain the two public methods: ConfigureServices and Configure

The ConfigureServices method defines the services that will be used by your app.

The Configure allows you to compose your request pipeline using Middleware. These are components used within an ASP.NET application pipeline to handle requests and responses. The HTTP pipeline consists of a number of request delegates, called in sequence. Each delegate can choose to either handle the request itself, or pass it to the next delegate.

You can configure delegates by using the Run,Map, and Use methods on IApplicationBuilder, but the Run method will never call a next delegate and should always be used at the end of your pipeline.

The Configure method of the pre-built template is built to do a few things. First, it configures an exception handling page for use during development. Then, it sends a response to the requesting web page with a simple "Hello World".

This simple Hello, World project can run now without any additional code being added. To run the app, and view it in your browser, press the Play (Triangular) button in the toolbar:

Run App

Visual Studio for Mac uses a random port to launch your web project. To find out what port this is, open the Application Output, which is listed under View > Pads. You should find output similar to that shown below:

Application Output displaying listening port

Open your browser of choice, and enter http://localhost:5000/, replacing the 5000 with the port that Visual Studio output in the Application Output. You should see the text Hello World!:

browser showing text

Adding a Controller

ASP.NET Core Apps use the Model-View-Controller (MVC) design pattern to provide a logical separation of responsibilities for each part of the app. MVC consists of the following:

  • Model: A class that represents the data of the app.
  • View: Displays the app's user interface (which is often the model data).
  • Controller: A class which handles browser requests, responds to user input and interaction.

For more information on using MVC refer to Overview of ASP.NET Core MVC guide.

To add a controller, do the following:

  1. Right-click on the Project name and select Add > New Files. Select General > Empty Class, and enter a controller name:

    New File dialog

  2. Add the following code to the new controller:

    using System;
    using Microsoft.AspNetCore.Mvc;
    using System.Text.Encodings.Web;
    
    namespace Hello_ASP
    {
        public class HelloWorldController : Controller
        {
            //
            // GET: /HelloWorld/
    
            public string Index()
            {
                return "This is my default action...";
            }
    
        }
    }
    
  3. Add the Microsoft.AspNetCore.Mvc dependency to the project by right-clicking the Dependency folder, and selecting Add Package....

  4. Use the Search box to browse the NuGet library for Microsoft.AspNetCore.Mvc, and select Add Package. This may take a few minutes to install and you may be prompted to accept various licenses for the required dependencies:

    Add Nuget

  5. In the Startup class, remove the app.Run lambda and set the URL routing logic used by MVC to determine which code it should invoke to the following:

    app.UseMvc(routes =>
    {
        routes.MapRoute(
        name: "default",
        template: "{controller=HelloWorld}/{action=Index}/{id?}");
    });
    

    Make sure to remove the app.Run lambda, as this will override the routing logic.

    MVC uses the following format, to determine which code to run:

    /[Controller]/[ActionName]/[Parameters]

    When you add the code snippet above, you are telling the app to default to the HelloWorld Controller, and the Index action method.

  6. Add the services.AddMvc(); call to the ConfigureServices method, as illustrated below:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
    

    You can also pass parameter information from the URL to the controller.

  7. Add another method to your HelloWorldController, as illustrated below:

    public string Xamarin(string name)
    {
        return HtmlEncoder.Default.Encode($"Hello {name}, welcome to Visual Studio for Mac");
    }
    
  8. If you run the app now, it should automatically open your browser:

    Running app in browser

  9. Try to browse to http://localhost:xxxx/HelloWorld/Xamarin?name=Amy (replacing xxxx with the correct port), you should see the following:

    Running app in browser with arguments

Troubleshooting

If you need to install .NET Core manually on Mac OS 10.11 (El Capitan) and higher, do the following:

  1. Before you start installing .NET Core, ensure that you have updated all OS updates to the latest stable version. You can check this by going to the App Store application, and selecting the Updates tab.

  2. Follow the steps listed on the .NET Core site.

Make sure to complete all four steps successfully to ensure that .NET Core is installed successfully.

Summary

This guide gave an introduction to ASP.NET Core. It describes what it is, when to use it, and provided information on using it in Visual Studio for Mac. For more information on the next steps from here, refer to the following guides: