Creating ASP.NET Core Web API in Visual Studio 2015

This tutorial lets us create very basic ASP.NET Core Web API using Visual Studio 2015. We will be creating Contacts API which lets 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. Update 12/10 – Updated to ASP.NET Core 1.0 with EF Core

What’s in this tutorial?

  • Contacts API Overview
  • Create ASP.NET Core Web API project
  • Create Contacts model
  • Create and Register repository class for Contacts
  • Add Contacts API Controller
  • Enable CamelCasePropertyNamesContractResolver
  • 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 Web API project

Install ASP.NET Core 1.0

Open Visual Studio 2015 Update 3, create “New Project” with name “ContactsApi

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


Creating ASP.NET Core Web API

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

Step 3: Packages included for ASP.NET Core Web API

The packages included are “MVC”, “EnvironmentalVariables”, “JSON”, “Logging”. (This is generated by default, do not copy this).

Step 4: Creating Contacts model

Contacts class is 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 5: 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 MVC 6 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 7

Step 6: Add Contacts API Controller

Its 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 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 7: Enable CamelCasePropertyNamesContractResolver

Any Web Api (REST based) should return JSON response in form of Camel Case so that we can sure consume the API in any client. We need to enable CamelCasePropertyNamesContractResolver in Configure Services.

Here is the Startup.cs file which has all code needed for running this Contacts ASP.NET Core Web API.

You may also like...

55 Responses

  1. pradeep CHAUDHARY says:

    what would be url to access the GetAll method over the browser?

  2. Gary says:

    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.

  3. Gary says:

    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.

  4. Réal Chartrand says:

    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.

  5. 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

  6. Hi Mithun,
    Have small doubt, for this ASP.NET Web API works for all the devices like Andriod, IOS etc.. if we host and call in different projects


    • 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

  7. 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.

  8. ganesh says:

    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?

    • This post have link for EF Core at bottom, read that.

      • ganesh says:

        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.

        • ganesh says:

          or How do I prevent an Item from being deleted if there is any sales entry for it.

        • 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.

          • ganesh says:

            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.

  9. miles says:

    Thanks, this was a great example to get started with Web API’s

  10. Abbid M Siddiqui says:

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

  11. Rachel says:

    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?

  12. Shane Thompson says:

    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.

  13. Sebastian says:

    thank you! very nice, no too simple not too complicated… just right to get started!

  14. 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’?

  15. Alva Chien says:

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

  16. Binod Nair says:

    Good work Mithun

  17. thomas yuen says:

    Thank for posting the source!!!

  18. Sandip Timsina says:

    Can you please do a similar tutorial on Authentication

  19. thomas yuen says:


    Can I get the source code to play around?

  20. Matt K. says:

    On Step 3, I think you meant to say “project.json,” not “package.json”

  1. June 9, 2016

    […] on from Basic Web API created using ASP.NET Core, we will create following files in our […]

  2. July 17, 2016

    […] Creating ASP.NET Core MVC 6 Web API in Visual Studio 2015 […]

  3. July 28, 2016

    […] Creating ASP.NET Core MVC 6 Web API in Visual Studio 2015 […]

  4. September 25, 2016

    […] Creating Basic ASP.NET Core MVC 6 Web API in Visual Studio 2015Jan 17, 2016 – This tutorial lets us create very basic ASP.NET MVC 6 Web API using Visual Studio 2015. We will be creating Contacts API which lets do … […]

  5. September 26, 2016

    […] Creating Basic ASP.NET Core MVC 6 Web API in Visual Studio 201517.01.2016 – NET Core MVC 6 Web API with C# 6 in Visual Studio 2015. … 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 … Json“: “1.0.0-rc2-final”,. […]

  6. September 26, 2016

    […] Creating Basic ASP.NET Core MVC 6 Web API in Visual Studio 2015Jan 17, 2016 – This tutorial lets us create very basic ASP.NET MVC 6 Web API using Visual Studio 2015. We will be creating Contacts API which lets do … […]

  7. October 12, 2016

    […] is continuation of Creating ASP.NET Core WebAPI, recommend to read it to move further here. You can still create your own project […]

  8. October 18, 2016

    […] Creating ASP.NET Core MVC 6 Web API in Visual Studio 2015 […]

  9. January 22, 2017

    […] Source: Creating ASP.NET Core Web API in Visual Studio 2015 […]

  10. February 16, 2017

    […] }, Kaynak : Sonra bunu postmande deneyebiliriz. Publish etmek içinde projemizi sağtıklayı publish […]

Leave a Reply