Building Web APIs with ASP.NET Core

Carlos Gómez
devops and cross platform development
3 min readJun 30, 2016

--

ASP.NET Core is a new open-source and cross-platform framework for building modern cloud-based Web applications using .NET.
With this new framework we have a consistent and unified experience for building both web UI and web API’s.

web api net core explanation

As we can see in the image the MVC and Web API framewrok share a bunch of concepts like controllers, actions, filters, dependency injection, model binding but they actually share no code at all, this is because historically MVC was tied to IIS and Microsoft wanted Web API to be able to be self hosted but this has proved to be a problem for developers because when we want to implement a feature for MVC or Web API we often end up implementing it twice.
So how can we fix this?
MVC + Web API + Web Pages = ASP.NET Core MVC. In ASP.NET Core we are aligning MVC, Web API and Web Pages into a single web stack so now we have both Web UI and Web API’s and we avoid duplication.

Web API features

  • Attribute routing
  • Model binding and validation
  • Link generation
  • Formatting JSON, XML
  • Metadata generation
  • Authorize access with JWT bearer tokens
  • JSON Patch
  • CORS

Install .NET Core and use it with Visual Studio

Download the Visual Studio official MSI Installer and the latest NuGet Manager extension for Visual Studio. You can download Visual Studio Community 2015 for free.

Let’s code

  1. File -> New Project -> Under Templates -> Visual C# -> Web -> Pick ASP.NET Core Web Application (.NET Core)
web api new project visual studio
  1. We need to select the Web API core template
web api core template visual studio
  1. Let’s dive into the code, open Program.cs
  • public static void Main(string[] args)
    {
    var host = new WebHostBuilder() //Wire up ASP.NET Core hosting
    .UseKestrel() //What server do I want to use — kestrel is a cross-platform server
    .UseContentRoot(Directory.GetCurrentDirectory()) // Where the app is going to find MVC views
    .UseIISIntegration() //This app is going to run behind IIS. The web.config define a native
    //module called aspNetCore that runs an IIS
    .UseStartup<Startup>() //The Startup define the actual application logic
    .Build();
  • host.Run();
    }
  1. Open the Startup.cs
  • public class Startup
    {
    //The main task of the contructor is setting up configuration getting the name value pair out of
    // a different configuration sources like JSON files, XML files, enviromental variables, etc..
    public Startup(IHostingEnvironment env)
    {
    var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile(“appsettings.json”, optional: true, reloadOnChange: true)
    .AddJsonFile($”appsettings.{env.EnvironmentName}.json”, optional: true)
    .AddEnvironmentVariables();
    Configuration = builder.Build();
    }
  • public IConfigurationRoot Configuration { get; }
  • public void ConfigureServices(IServiceCollection services)
    {
    // Setting up all of the services that I want to be made available to my app via
    // dependency injection, in this example MVC is adding its services to the sevice collection
    // and making them available to every one
    services.AddMvc();
    }
  • // This method sets up the HTTP request pipeline for our app.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
    loggerFactory.AddConsole(Configuration.GetSection(“Logging”));
    loggerFactory.AddDebug();

    // We’re using MVC middleware (MVC is built on top of generic routing middleware) and we just set up
    // MVC as route handler for the route middleware
    app.UseMvc();
    }
    }
  1. Finally let’s run the app
web api project first run result
  1. We just got some values back from the ValuesController
  • [HttpGet]
    public IEnumerable<string> Get()
    {
    return new string[] { “value1”, “value2” };
    }

Note: In comming blog post I’ll dive in some Web API features


Source code: https://github.com/devcfgc/web-api-asp-net-core


Part one: Building Web APIs with ASP.NET Core
Part two: Building Web APIs with ASP.NET Core — Attribute routing

--

--

Cloud/Software Architect and DevOps learning about #devops, #cloud, #netcore, #microservices and #newtech