ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients. In this blog, we will cover how to build a Web API controller in ASP.NET using C#, including creating the controller, routing requests, and returning data.
To create a new Web API controller in an ASP.NET application, you can use the "Add Controller" feature in Visual Studio. Here's an example of how to create a simple Web API controller that returns a list of products:
using System.Collections.Generic;
using System.Web.Http;
namespace MyWebApp.Controllers
{
public class ProductsController : ApiController
{
// GET api/products
public IEnumerable<string> Get()
{
return new string[] { "Product 1", "Product 2", "Product 3" };
}
}
}
In the example above, we created a new class called ProductsController that inherits from the ApiController class. This base class provides a lot of the functionality needed to build a Web API controller, including handling HTTP requests and responses.
Next, we added a method called Get that will handle GET requests to the "/api/products" endpoint. This method simply returns a list of strings representing product names.
To route requests to this controller, we need to add a new route to the application's routing configuration. Here's an example of how to do that in the Global.asax file:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
In the example above, we're using the MapHttpRoute method to add a new route to the application. This route specifies that any requests to "/api/{controller}" will be handled by a controller with a matching name, and that any additional parameters (in this case, an "id" parameter) will be passed to the controller method as an argument.
Finally, to test our new controller, we can use a tool like Postman to send a GET request to the "/api/products" endpoint. If everything is configured correctly, we should see a JSON response containing the list of product names that we defined in our controller.
In conclusion, building a Web API controller in ASP.NET using C# is a straightforward process that can be accomplished with just a few lines of code. By leveraging the built-in functionality of the ApiController base class and the application routing configuration, we can quickly and easily create powerful APIs that can be consumed by a wide range of clients.