In this article I am going to explain
how to create Web API first Hello world application.
I am using Visual studio
2019 and .net framework to create this application.
Implementation:
STEP 1 :
Open VS 2019. Click on create a new project and select ASP.Net web application
(.Net Framework).
STEP 2 : Configure
new project window will be open. Enter the project Name, select location and
click on Create button.
STEP 3 :
Create a new ASP.NET Web application window will be open. Select Empty and
check the Web API from add folders & core reference. If you want to create MVC
+ Web API, then select the MVC option.
Application will be
created and looks as below attached screenshot.
Firstly, you need to check
the important files of Web API application WebApiConfig.cs
and Global.asax
WebApiConfig.cs
This file is very
important because it configure the routes of incoming request. This file is
located under App_Start folder and
looks as shown below:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web
API configuration and services
// Web
API routes
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.asax
This file has
Application_Start method. This method is executed when application starts for
first time. As you see Web API routes are configured in this method. If you
check the definition of this, will redirect you to WebApiConfig.cs file.
protected void
Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
STEP 4 :
Now
let move to next step. Add controller to project. Right click on Controllers folder
>> Add >> select Controller. Select Web API 2 Controller-Empty,
click on add button and enter controller name.
STEP 5 : Create
a method. I have created a method (HelloMethod) and return the first application
text.
Complete
code of Controller (HelloController.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEBAPI.Models;
namespace WEBAPI.Controllers
{
public class HelloController : ApiController
{
[HttpGet]
public string
HelloMethod()
{
return "Web API Hello World (First
Application)";
}
}
}
All done, now run the application. Type the URL according to
WebApiConfig.cs file like Api/controller/Action/id e.g. https://localhost:44373/api/hello
Confused :-(.....I can't trace where the url becomes /hello?
ReplyDeleteI figured it out :-( I guess the prefix is something important ;)
ReplyDeleteThanks for sharing btw