How to setup a minimal Web API in ASP.NET Core

Feel like playing around with the new .NET Core bits? Do you wonder how little code is needed to setup a Web API on .NET Core? Then this post is right up your alley!

Prerequisites

The .NET Core bits(dot.net), Visual Studio Code (code.visualstudio.com), but any editor will do

Setup

The plan is to create a new project with the help of the new .NET Core tools. Then add just enough dependencies and code to get a basic Web API up and running.

Creating the Web API

  1. Create a folder for the project and position in the folder in your favorite CLI
  2. Type “dotnet new” to create a basic project
  3. Type “code .” to open up Visual Studio Code
  4. Add the following to the dependencies section in project.json
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final"
    
  5. Run a package restore with “dotnet restore”
  6. Open Program.cs and add a using statement for “Microsoft.AspNetCore.Hosting”
  7. Modify the Main method in Program.cs it accordingly
     public static void Main(string[] args)
            {
                   var host = new WebHostBuilder()
                    .UseKestrel()
                    .UseStartup<Startup>()
                    .Build();
    
                host.Run();
            }
    
  8. Add a Startup.cs file in the root and edit it as follows
    using Microsoft.AspNetCore.Builder;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace ConsoleApplication
    {
        public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
            }
    
            public void Configure(IApplicationBuilder app)
            {
                app.UseMvc();
            }
        }
    }
    
  9. Add a “Controllers” folder
  10. Add a GrettingController.cs file in the folder and add the following code
    using Microsoft.AspNetCore.Mvc;
    
    namespace ConsoleApplication
    {
        [Route("api/[controller]")]
        public class GreetingController
        {
            [HttpGet]
            public string Get()
            {
                return "Greetings from .NET Core Web API!";
            }
        }
    }
    
  11. Position in the root folder and build the project with “dotnet build”
  12. Run the project with “dotnet run”
  13. Open a browser and hit “http://localhost:5000/api/greeting”

Given everything worked as planned, you’ll now see the merry greeting in your browser!

Get the code

The code is available on my GitHub account.

Happy Coding! 🙂

Minimal Web API on ASP.NET Core
Tagged on:             

8 thoughts on “Minimal Web API on ASP.NET Core

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.