Web Api 2 - Hello World example
We are going to create a new Web Api simple application which return to us Json with message and user name.
Lets start! First create new Web Api project using Visual Studio and select Empty Template. Be sure to check "Web Api" folder:
NOTE I didn't choose "Web Api" template because it adds reference to ASP.NET MVC to provide API Help Page. And in such basic application we don't really need it.
Adding a model
A model is an C# class that represents some data in our app. ASP.NET Web API is able to automatically serialize model to JSON, XML, or some other format (depends on configuration).
In our application we will create only one model, but real-world apps usually have a lot of them.
In Solution Explorer, right-click the Models folder. Next select Add and then select Class. Name the class "HelloMessage". Our model needs two properties: MessageText and UserName:
namespace WebApiHelloWorld.Models
{
public class HelloMessage
{
public string MessageText { get; set; }
public string UserName { get; set; }
}
}
Adding a controller
A controller handles HTTP requests. Our app needs only one controller that returns Json with Hello message and user name (which we will pass in URL).
In Solution Explorer, right-click the Controllers folder. Next select Add and then select Controller. In the opened window, select Web API Controller - Empty and click Add.
Set controller name as "HelloController". Next edit code of created controller. We need to add method which returns Hello message.
using System.Web.Http;
using WebApiHelloWorld.Models;
namespace WebApiHelloWorld.Controllers
{
public class HelloController : ApiController
{
public HelloMessage GetMessage(string name)
{
HelloMessage message = new HelloMessage
{
MessageText = "Hello my Dear!",
UserName = name
};
return message;
}
}
}
NOTE Be sure to add using WebApiHelloWorld.Models
. Without it your controller won't find HelloMessage class.
Finish
That's all! Now you only need to build and start your application. Simply hit Ctrl + F5 or just F5 (to start without debugging). Visual studio will launch web browser. You need to call your controller. To do that add at the end of the URL "/api/hello?name=John". The result should be:
{
"MessageText": "Hello my Dear!",
"UserName": "John"
}