Creating ASP.NET Core 2 Web API in Visual Studio 2017

This tutorial lets us create very basic ASP.NET Core 2 Web API using Visual Studio 2017. We will be creating Contacts API which let’s do popular CRUD operations.

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices.

ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

What’s in this tutorial?

  • Contacts API Overview
  • Create ASP.NET Core 2 Web API project
  • Create Contacts model
  • Create and Register repository class for Contacts
  • Add Contacts API Controller
  • Writing Contacts CRUD methods
  • Testing WEB API using POSTMAN

Step 1: Contacts API Overview

The Contacts API is very simple, basic Web API which does CRUD operations. I have focused on writing web API rather than integrating it with databases.  This table summaries Contacts API which we’ll create

API NameDescriptionRequestResponse
GET /api/contactsGets all ContactsNoneCollection of Contacts items
GET /api/contacts/{id}Gets Contact item by IDNoneContact item
POST /api/contactsAdds new Contact to collectionContact itemContact item after added
PUT /api/contacts/{id}Updates existing Contact item Contact itemNone
DELETE /api/contacts/{id}Deletes a Contact itemNoneNone

Step 2: Create ASP.NET Core 2 Web API project

Install .NET Core 2.0 SDK and Visual Studio 2017 (15.3)

Open Visual Studio 2017, create “New Project” with name “ContactsApi

From ASP.NET Core templates select “Web API”  for ASP.NET Core 2.0 (I haven’t selected any Authentication, we will add them later)

Program.cs file is an entry point when application run, that’s right public static void main(). ASP.NET Core apps are considered as console apps.

Step 3: Creating Contacts model

Contacts class is the centre of this Web API project. Its POCO class containing some properties which are self-explanatory.

Right click “ContactsApi” solution, create folder “Models“; under this “Models” folder create C# class “Contacts.cs” and copy this code

Step 4: Create and Register repository class for Contacts

The use of repository classes is really optional, but I have added it so that we can connect to any databases later.

Create “Repository” folder under “ContactsApi” solution, we will add one C# interface file and C# class file implementing this interface.

Create “IContactsRepository.cs” interface file in “Repository” folder and copy below code

Create “ContactsRepository.cs” class file, implement “IContactsRepository” and copy below code

ASP.NET Core 2 provides out of box support for Dependency Injection, we will include that in our “ConfigureServices” method of Startup.cs.  We will see entire code in Step 5

Step 5: Add Contacts API Controller

It’s time to add the controller API which acts as Web API. Create “Controllers” folder under “ContactsApi” project solution and add C# class file “ContactsController.cs“; copy below code

Some quick notes of this ContactsController

  1. [Route("api/[controller]”)] – this used attribute based routing to access the ASP.NET Core Web API.
  2. ContactsRepo is instantiated using dependency injection which we configure in services.cs.
  3. GetAll() is simple HttpGet method which gets all contacts
  4. GetById fetches contact based on the mobile phone. Its given HttpGet with Name attribute so that we can use that in Create method to be used for location header.
  5. Create method after inserting contact, returns 201 response and provides location header.

Note: HTTP Status codes are now written as BadReqest(), NotFound()Unauthorized() etc

Step 6: Testing Contacts Web API using POSTMAN

ASP.NET Core 2 Web API allows disabling of launching browser when we debug the application. Right click on “ContactsApi“, goto “Properties” and Select Debug.

You can uncheck “Launch URL” check box to ensure it doesn’t the open browser (this is optional). RUN/ DEBUG application by clicking “IIS Express” which starts Web API, we can use other ways to start the application.

Since Web API does CRUD operations on Contacts using in memory collections. we will start with POST, GET, PUT, DELETE operations

Using Chrome’s POSTMAN extension to test client, it’s very easy to use. Even Fiddler can also be used for testing.

Contacts API’s POST operation
ASP.NET Core 2 Web API

Contacts API POST operation

Point 2 provides location header which can be used fetch result.

Contacts API GET operation
ASP.NET Core 2 Web API

Contacts Api GET operation

Contacts API PUT operation
ASP.NET Core 2 Web API

Contacts Api PUT operation

Contacts API DELETE operation
ASP.NET Core 2 Web API

Contacts Api DELETE operation

This sample will be made better by adding logging, connecting to the database using EF Core or EF 6 or any ORMs.

Read Integrating EF Core with ASP.NET Core 2 Web API

The source code of this article is at mithunvp github repo

Leave a Reply

  1. very nice. I can use postman to test on my local machine, but I am not quite sure how to deploy it to a server so it can be used. can you point me in the right direction?

  2. Pingback: Homepage

  3. Pingback: Homepage

  4. I am new to Web API and I have successfully build your source code after downloading it from github. I am confused how to run and use it in my localhost or using postman? What would be the url ? Will it be something like http://localhost:82/api/contacts to view it in a browser.

  5. Perfect..Thanks for the post. Do we need to run this command “dotnet ef migrations add init” every time we create a model.

    • Only when you change the data models (adding new class, changing to existing model), we need to call dotnet ef migrations “short name of changes”, also update the database so that changes take effect.

  6. Hello – I had one more comment – in the last part of the posting you said the listing below had all the Startup.cs code in it to run the app but the only thing listed is a ConfigureServices.cs item. Thank you.

  7. Hello – great article but a couple of items I do not see. You listed the CRUD methods and Postman testing but I do not see the methods and, since I am new to building APIs using .NET, I was looking forward to the Postman testing section. You also said that you had provided your gitHUB link for the code but I also cannot find it in the posting.

  8. Pingback: Core ile Web Api | Tuğba Şahin

  9. Pingback: Creating ASP.NET Core Web API in Visual Studio 2015 | ASP.NET

  10. Really a nice example of using EF core with webapi aspnet core. I new with EF core webapi core, all is working perfectly with visual studio 2015 update 3 and server kestrel self-hosting scenarios. But when i publish on IIS 7.5 the api/Values work fine and Api/Contacts this api use EF Core not work.

    I have the impression that it needs to add files in the include part of publishOptions in projectc.json, but I do not see which ones. Your help would be more than appreciate.

    Please excuse my English.

  11. Mithun,
    1. Could you please provide, How can I get the source code from Git Hub Repo.
    2. If I want to keep this webapi as one layer in my project, and call the controller in another layer, is it possible any examples regarding those.

    Thanks In Advance

    • Yes, this web API projects works for different JS frameworks (Angular, Jquery, Knock out) , devices(android, iOS, Windows Phone, desktop apps like (WPF, Windows Forms) and non .NET desktop applications.

      Host the web api project on IIS(windows OS, Azure, Linux also using Ngnix) and call it using the URLs

  12. It’s a really helpful post! How can I use core web api with mysql database? I do not want to create tables manually, but I guess it should be possible through some command and some settings. Or even perhaps through simple clicks in visual studio.

    • Thanks for your comment. I have an article of using EF Core with Sql Server, refer that. When using MySQL the appropriate provider need to used.

      At present for EF Core tooling, you can create tables manually only. With EF, you need to create migrations and then update database.

  13. Thanks Mithun for this post it is really helpful.
    I am new to, worked a lot with desktop apps now migrating to
    how do we read contacts from local sql server database?
    where to set the sql server connection string?

      • Thanks sir, It was of great help.
        I have developed a desktop app and want to convert it to web/mobile app.
        The existing design have different ms sql 2012 express edition databases for Masters and Transactions with multiple tables.
        i.e. MasterDB with Item, Customer, etc tables
        and TransactionDB with Purchase, Sales, Stock, etc tables
        My question is that how do I validate if Stock for any Item_Id (Item table in MasterDB) exists (in Stock table in TransactionDB)
        before saving any sales entry.
        In my desktop app I check it by querying the stock table by beginning a sql Transaction and Rollback if stock does not exists as there are some more validations before committing the sales transaction.
        Wish you a very happy Diwali.

        • Thanks Ganesh and Happy Deepavali too !!
          ASP.NET web apps work on disconnected architecture, in your case multiple db’s are involved so obviously desktop approach wont work.

          Don’t use transaction, instead create services for these kinds of business rules. If the services return positive response then proceed to save data. If response is negative you can prevent further operations.

          Hope this helps you.

          • Thanks for your valuable suggestion.
            Do you mean WCF services.
            My Question is how do I implement business rules. i.e. while saving sales entry I have the following steps:
            1) check if there is a valid sales order.
            2) generate next invoice no.
            3) check if stock is available for Item_Id, if true, update Stock table.
            3) check if there is enough balance credit for customer AcBalance table, if true update AcBalance table.
            4) Post entry to Tax Register, Sales Register.

            If validation fails at any step I need to rollback all previous crud(Insert/update) actions
            Also multiple users are adding sales entry so I need to lock records in Stock table so that same stock is not sold by two persons (How do I manage concurrency?)

          • Ganesh,
            Many requirements are to be met. Only this I can say is dont do business rule at end, try them before. Like Stock not available, then dont allow to order, no credit balance or order more than balance then dont allow to order.

  14. Pingback: ¿Cómo construimos nuestro Framework para desarrollo Mac / Windows (Parte I) | HORIZON Soft & Apps

  15. Pingback: Integrating ASP.NET Core Web API and Entity Framework Core

  16. Pingback: mvc login tutorial - دسرا

  17. Pingback: asp net web api json - دسرا

  18. Pingback: web api tutorial | bruinrow

  19. Can you please share the code for data context or the steps to create an underlying Contacts table using code first?

  20. Pingback: ¿Cómo construimos nuestro Framework para desarrollo? (Parte I) | HORIZON Soft & Apps

  21. Pingback: Creating CRUD ASP.NET Core MVC 6 Web API in Visual Studio 2015 | aspnet core mvc

  22. Hello! Your tutorial helped me out on starting my own web api! But can you do a tutorial on one to many or many to many relationships for web api? For examples if the contacts have multiple emails?

  23. that’s a really awesome tutorial and was very helpful to learn from! Can you please help me with one question though?

    I am new to and MVc6 and I’ve been learning how to create a webapi.

    I was wondering what if you had apis??

    /api/contacts and /api/meetingrooms (or something)

    how would you access all of the properties of contacts from meetingrooms and vice versa? or am i somehow missing the point?


    • Thanks Shane for encouraging words.
      We need to design underlying data schema as many to many relationships (in your case).
      /api/contacts should deal with contacts only, if you want to include meeting rooms design API response data to send meetings rooms based on some queries or vice versa.

  24. Pingback: ASP.NET Core Middleware - Writing a Custom middleware in Web API

  25. Thanks for the great article. I am new to WebAPI and this tutorial help ed me kickoff my journey towards WebAPI.
    I had VS2015 Professional Update 1 installed on my machine. I have followed the tutorial and it worked fine, however after upgrading the Visual studio to Update 2, I started getting below error in the Startup.cs Main(…) method on WebApplication.Run(…)

    An unhandled exception of type ‘System.InvalidOperationException’ occurred in Microsoft.Extensions.DependencyInjection.Abstractions.dll
    Additional information: No service for type ‘Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment’ has been registered.

    It works fine on my colleague machine who didn’t upgrade to Update 2.

    Not sure how to overcome this.
    Also, Now I am not getting 5 Templates for the new project.
    Looks like something is missing after the Update 2.

    I tried to uninstall the Update 2 and it corrupted Visual Studio. Tried Repair/Uninstall/Install and same error reported.

    Can you help me resolving the issue of ‘IApplicationEnvironment’?

  26. That’s a very good example for building API. But how about the security part since the API shall be protected?