Getting Started with ASP.NET Web API - 1

Creating First Service Using Web API for beginners


Category: ASP.NET Tags: WebApi, C#, MVC, MVC4, ASP.NET


Web API Introduction:

ASP.NET Web API is a framework for building web APIs on top of the .NET Framework, it is all about creating restful web services. In this article I will show you how to start with Web API.

Project Setup:

In your visual studio. Go to File -> New -> Project and select the template ASP.NET MVC4 Web Application (you will have to install MVC4 or later version to use Web API Framework) give a project name like “WepAPIBeginning” click OK  then you will see some other templates like :


  
Now select the Web API template and click OK.
It will automatically add the references of Entity Framework and MVC4 to the project.

My First API:

For creating your first API right click on folder called “controllers” in solution explorer and go to Add and click on controller, name it MyFirstAPI (the full name will be MyFirstAPIController) and select Empty API Controller Template, click Add.

you will see a class like :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WepAPIBeginning.Controllers
{
public class MyFirstAPIController : ApiController
{

}
}

** Same as MVC controller inherits the Controller class, API controller inherits the ApiController class.

Now create a simple method in this class named “Hello” like this:
 [HttpGet]
public string Hello(string name)
{
     return "Hi, " + name;
}
Now add the routing, go to App_Start -> WebApiConfig
And add the following routing:
config.Routes.MapHttpRoute(
name: "HelloApi",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: new {}
);
Here this method is get type, now run the project. It will take you to the link something like:
https://localhost:1620/
and change it to:
https://localhost:1620/api/MyFirstAPI/Hello?name=nikhil
The output will be:
<string xmlns="https://schemas.microsoft.com/2003/10/Serialization/">Hi, nikhil</string>

The output will be in xml, you can use REST Client and get output in both JSON or XML. And even can do more like prettify, adding headers and calling post services.

In Rest client your output will look like:

Hi, nikhil

Like 1 Person
Last modified on 11 October 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 135
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x