Creating First ASP.Net Core Web API Application

I am back with my second post on .Net Core focusing on ASP.Net Core. This time I am going to try a ASP.Net core Web API application. This will be a starter application to show the basics of Asp.Net Core Web API. In the future posts I will be building on top of this application. Lets start with the application.

I will be using Visual Studio 2017 Community edition for building this application. For downloading the Visual Studio 2017 community edition, you can click the download link and download. Or you can just google and download. I have already downloaded and installed it in my PC, so I am going to just start with opening the Visual Studio from my start menu. I will be using my Windows 10 PC for this development.

Creating the first ASP.Net Core application

First of all I am going to open Visual Studio 2017, after that I am going to select the “Create New Project” option from the “Start Page” tab. This will open up the New Project model window. In the New Project model window, I am going to select “Web” -> “ASP.NET Core Web Application” and give the name of the project “MyFirstWebApplication” and click “OK“.

ASP.Net Core Web API

This will popup a new window with the option to select version of ASP.Net with “.NET Core” and “ASP.NET Core 2.0” selected by default. Other option is “.Net Framework” and ASP.NET Core 2.0. I will keep the default options and select “Web API” from the project templates available and click “OK“. At this point I am not going to try other fancy features like Docker support, maybe later since I am still at the very beginning.

ASP.Ner Core Web API selection

As a result of the above steps, Visual Studio will create the necessary scaffolding for creating my first Web API application. We can do the same thing using the CLI, but I want to start with Visual Studio as it is my tool of choice for day to day development work. The project is now ready with all necessary files. The main files to consider are as follows:

  1. Program.cs – This file contains the Main method, which will use Startup.cs to configure the application.
  2. Startup.cs – This file contains all the bootstrapping logic
  3. ValueController.cs – The default API controller.

ASP.Net Core Web API Project View

Code inside Program.cs

The Program.cs contains the following code:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();
}

The main method of interest here is WebHost.CreateDefaultBuilder. Calling this method initializes a new instance of the WebHostBuilder with default configuration. Calling the method UseStartup<Startup> on the WebHostBuilder instance tells the WebHostBuilder instance to use Startup instance during runtime configuration. The Startup instance is be used runtime to setup different services and configuring HTTP request pipeline.

Code inside Startup.cs

The Startup.cs contains the following code:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

In this class the default comments provided explains everything. The method ConfigureServices is where you would add new services to the container. By default MVC service is added. The method Configure will be used for configuring HTTP request pipeline. By default the MVC is added to the pipeline. This class is convention driven, and the method names has to be exactly same for the runtime to call them. These methods are optional.

Code inside ValueController.cs

The ValueController.cs contains the following code:

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

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

This is a standard Web API controller with GET, GET, POST, PUT and DELETE methods. The base route is configured at the class level using Route attribute. Here the [controller] is the name of the controller excluding the Controller section, in this case the route would be /api/values.

Running the application

In the current default configuration, the application is set up to run in IIS Express. My preference is to run as self host for the intranet application, as it is much easier and faster to configure, start and it also consumes less memory. Hence I am going to change it to run as self host console application. For that I am going to change the Run option from IIS Express to MyFirstWebApplication. As soon as I hit F5, the self host console starts and the API url for the GET method http://localhost:59290/api/values opens up in my Edge browser with the default JSON response.

Conclusion

In conclusion this was very easy and simple to start with a ASP.Net Core Web API application. I hope this post helps you. If you need any detailed explanations of any of the sections, please leave me a comment and I will update the post with the details.

I have a video with the steps followed for creating the console application, here is the link to the YouTube video.

References

Microsoft Documentation: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api