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

You may also like...

63 Responses

  1. lsfzheng says:

    where should i paging,search,sort logic in this program

  2. dan hillman says:

    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?

  3. Faheem says:

    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.

  4. shyju says:

    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.

  5. pradeep CHAUDHARY says:

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

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

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

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

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

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

    Thanks
    Bhanu.

    • 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

  11. It’s a really helpful post! How can I use asp.net 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.

  12. ganesh says:

    Thanks Mithun for this post it is really helpful.
    I am new to asp.net, worked a lot with desktop apps now migrating to asp.net.
    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 vb.net desktop app and want to convert it to asp.net 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.

  13. miles says:

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

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

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

  16. 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 asp.net 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,

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

  17. Sebastian says:

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

  18. Thanks for the great article. I am new to ASP.net WebAPI and this tutorial help ed me kickoff my journey towards ASP.net 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 ASP.net 5 Templates for the new ASP.net 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’?

  19. Alva Chien says:

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

  20. Binod Nair says:

    Good work Mithun

  21. thomas yuen says:

    Thank for posting the source!!!

  22. Sandip Timsina says:

    Hi
    Can you please do a similar tutorial on Authentication

  23. thomas yuen says:

    HI,

    Can I get the source code to play around?

  24. 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 : http://www.mithunvp.com/create-aspnet-mvc-6-web-api-visual-studio-2015/ Sonra bunu postmande deneyebiliriz. Publish etmek içinde projemizi sağtıklayı publish […]

  11. July 15, 2017

    … [Trackback]

    […] Read More Infos here: mithunvp.com/create-aspnet-mvc-6-web-api-visual-studio-2015/ […]

  12. October 1, 2017

    … [Trackback]

    […] Read More: mithunvp.com/create-aspnet-mvc-6-web-api-visual-studio-2017/ […]

Leave a Reply