Skip to main content

Your First ASP.NET Web API in Action.

ASP.NET Web API is a framework for building Web APIs on top of the .NET Framework. In this tutorial, we’ll create a web API in ASP.NET to become familiar with Web API.

So let’s start J

Open Visual Studio IDE > Create New Project > Under Web Template > Select ASP.NET MVC 4 Web Application > and provide a name (in this case TestWebAPI) and select the location.


On next screen select “Web API” under template and click OK.


Your default WebAPI project is created and ready for use; let’s have a look at the file and directories of the default project.


Folders
Description
App_Data
This folder contains application data files.
App_Start
Contains different configuration files
Content
All the themes and styles files are added under this folder.
Controllers
Conations Web API controllers
Images
Contains Images of the project
Models
Models folder used to create Model under it, by default there is no Model.
Scripts
All the client script files located under this folder.
Views
All the MVC views located under this, by default you can see some views as well.
Beside that there is Web.Config and Global.asax files.

We have understood the directory structure, now we’ll create a simple WebAPI.

Add a Model:
A model is nothing but a class file having properties that represent the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other required format, and then write the serialized data into the body of the HTTP response message.

Let's create a simple model for Customers > Right-click the Models folder and add a new Class and add four properties in the class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestWebAPI.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string City { get; set; }
    }
}

Add a Controller
A controller is an object that handles HTTP requests. If you are an ASP.NET MVC developer, then you are already familiar with controllers. But controller in Web API derives from the ApiController class instead of the Controller class. Another major difference is that actions on Web API controllers return data instead of views.

Under the Controllers folder, by default there are two controllers:
·         HomeController is not directly related to Web API and it is an ASP.NET MVC controller.
·         ValuesController is an example Web API controller with empty read/write actions.

Let’s delete ValuesController, and then add a new controller as follows:

Right-click on the Controllers folder > Select Add and then select Controller > Enter controller name (i.e. CustomerController in this case) and select a template, there are different options available there, we’ll go with Empty API controller.


Now our Controller is ready to use, open this controller and replace the code in this file with the following:

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using TestWebAPI.Models;

namespace TestWebAPI.Controllers
{
    public class CustomerController : ApiController
    {
        List<Customer> customers = new List<Customer>
        {
            new Customer {Id=1, Name = "Sandeep Kumar", Email = "sandeep@test.com", City = "Gurgaon" },
            new Customer {Id=2, Name = "Customer1", Email = "customer1@test.com", City = "Gurgaon" },
            new Customer {Id=3, Name = "Customer2", Email = "customer2@test.com", City = "Gurgaon" },
            new Customer {Id=4, Name = "Customer3", Email = "customer3@test.com", City = "Gurgaon" },
            new Customer {Id=5, Name = "Customer4", Email = "customer4@test.com", City = "Gurgaon" }
        };

        public IEnumerable<Customer> GetCustomers()
        {
            return customers;
        }

        public Customer GetCustomerById(int id)
        {
            var customer = customers.FirstOrDefault(c => c.Id == id);

            if (customer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            return customer;
        }
    }
}

In this controller class, we have used a fixed list of Customers; you can get it from DB or any other external data source as per your convenience.

The CustomerController defines two methods that return customers:

·         The GetCoustomers method returns all the customers.
·         The GetCustomerById method returns a single customer by its Id.

So now we have a fully functional Web API ready for use, each method on the controller maps to a URI through which we can access our API by sending an HTTP GET request:

Controller Method
Mapping URI
GetCoustomers
/api/customer
GetCustomerById
/api/customer/id

Let’s see Web API in action now, run the application, and by default, it’ll open the default page.

Access Web API with mapping URI mentioned above to see the result.


All Customers
customer by Id 
That’s it for now; you can also download the sample code of this post.

In the next article, we’ll call our Web API methods with the help of jQuery.

Comments

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...