Set up an API controller in .NET using C#
Create a new project in Visual Studio
Create a new project in Visual Studio by going to File > New > Project and choosing the appropriate project type. For this example, we will create a new ASP.NET Core Web Application project.
Add a controller
Add a new controller by right-clicking on the Controllers folder in the Solution Explorer and selecting Add > Controller. Choose the appropriate controller type depending on your project needs. For this example, we will add an empty API controller.
using Microsoft.AspNetCore.Mvc;
namespace MyProject.Controllers
{
[ApiController]
[Route("[controller]")]
public class MyApiController : ControllerBase
{
// Controller actions will be defined here
}
}
Define the controller actions
In the new controller class, define the various actions (methods) that the API will support. These actions should correspond to the various HTTP methods that the API will handle, such as GET, POST, PUT, and DELETE.
[HttpGet]
public ActionResult<string> Get()
{
return "Hello, world!";
}
[HttpPost]
public ActionResult<string> Post([FromBody] string value)
{
return $"You posted: {value}";
}
[HttpPut("{id}")]
public ActionResult<string> Put(int id, [FromBody] string value)
{
return $"You updated the value of item {id} to: {value}";
}
[HttpDelete("{id}")]
public ActionResult<string> Delete(int id)
{
return $"You deleted item {id}";
}
Decorate the actions with HTTP attributes
Each action in the controller should be decorated with an HTTP attribute that specifies the HTTP method that it will handle. For example, an action that handles GET requests should be decorated with the [HttpGet]
attribute.
Define the action parameters
Each action in the controller should define the parameters that it expects to receive from the client. These parameters can be specified as method arguments or as properties on a model class.
[HttpPost]
public ActionResult<string> Post([FromBody] string value)
{
return $"You posted: {value}";
}
[HttpPut("{id}")]
public ActionResult<string> Put(int id, [FromBody] string value)
{
return $"You updated the value of item {id} to: {value}";
}
Implement the action logic
Within each action, write the logic that will handle the incoming request and generate the appropriate response. This may involve retrieving data from a database, performing some business logic, and returning the results in a specific format such as JSON.
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var items = new List<string>
{
"Item 1",
"Item 2",
"Item 3"
};
return Ok(items);
}
[HttpPost]
public ActionResult<string> Post([FromBody] string value)
{
// save the value to the database
return CreatedAtAction(nameof(Get), new { id = 1 }, value);
}
Configure routing
Finally, you will need to configure the routing for your API, which determines how incoming requests are mapped to the appropriate controller action. This can be done in the Startup.cs file using the MapControllerRoute
method.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}");
});
Once you have completed these steps, your API controller should be up and running and ready to handle incoming requests from clients.