In this tutorials, we will see the steps to set up your development environment and create a new project in ASP.NET Web API. Here is a step-by-step guide to help you get started.
Here we will cover the following.
1. Prerequisites
2. Create a New ASP.NET Web API Project
3. Understand Project Structure
The new project will have a structure similar to an ASP.NET Core application. Key files and folders include.
4. Create a Web API Controller
5. Impement API Actions
Within your controller, define the methods that will handle incoming HTTP requests and return responses. For example, a simple GET method might look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApiExample.Controllers
{
public class UserController : ApiController
{
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
private static List users = new List()
{
new UserModel { Id = 1, Name = "Rohatash" },
new UserModel { Id = 2, Name = "Rahul" },
new UserModel { Id = 3, Name = "Deepak" }
};
// GET api/user
public IHttpActionResult Get()
{
return Ok(users);
}
}
}
6. Run the Web API
Press F5 or click on the Run button in Visual Studio to start the Web API project. The Web API will launch in your default web browser, and you should see an API page or a response depending on the actions you've implemented.