How to create web api in asp.net c# without mvc

Creating a Web API in ASP.NET with C# without MVC

In order to create a Web API in ASP.NET with C# without using the MVC framework, you can follow these steps:

  1. Create a new ASP.NET Empty Web Application project in Visual Studio.
  2. Add a new class file to the project which will act as the Web API controller.
  3. Implement the API endpoints by defining methods inside the controller class.
  4. Configure the Web API routing.
  5. Run the application to test the API.

Here’s an example:

using System;
using System.Web.Http;

namespace WebApiExample
{
    public class ValuesController : ApiController
    {
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok("Hello, World!");
        }
        
        [HttpPost]
        public IHttpActionResult Post([FromBody] string value)
        {
            // Process the posted value
            return Created("api/values", value);
        }
    }
}
    

In this example, we have defined two API endpoints:

  • GET /api/values: Returns a simple greeting message.
  • POST /api/values: Expects a string value in the request body and returns a status code and the posted value.

To configure the routing, add the following code to the Application_Start() method inside the Global.asax.cs file:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
}
    

Then, create a new class file called WebApiConfig.cs and define the following:

using System.Web.Http;

namespace WebApiExample
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
        }
    }
}
    

This enables attribute routing for your Web API.

Finally, run the application and navigate to /api/values to test the “GET” endpoint, and use a tool like cURL or Postman to make a “POST” request to /api/values with a JSON payload containing the value you want to post.

This is a basic example of how to create a Web API in ASP.NET with C# without using the MVC framework. Feel free to expand on this by adding more endpoints and functionality as needed.

Leave a comment