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
- Create a folder for the project and position in the folder in your favorite CLI
- Type “dotnet new” to create a basic project
- Type “code .” to open up Visual Studio Code
- 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"
- Run a package restore with “dotnet restore”
- Open Program.cs and add a using statement for “Microsoft.AspNetCore.Hosting”
- 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(); }
- 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(); } } }
- Add a “Controllers” folder
- 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!"; } } }
- Position in the root folder and build the project with “dotnet build”
- Run the project with “dotnet run”
- 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
Pingback: How to Master ASP.NET Core Web API Attribute Routing | mobilemancer
Step 8. Startup.c should be Startup.cs.
Sorry about that, it’s fixed now.
Thanks for the help 🙂
Tried this, but the server didnt start
How did you try and start it, what error did you get?
I can see this article as somewhat a breakdown for the yeoman scaffolding “yo aspnet”.
Yes, I haven’t looked at the scaffold in a while, but this is what should be done basically.
Pingback: How to: Build a Web API on ASP.NET Core for an Aurelia SPA - mobilemancer