Saturday, April 5, 2025

.Net Core | Web API Basics

Web API is REST based web service.

Why Web API?
  1. Reuse logic for internal application
  2. Reuse logic for external application
  3. Separation of concerns
  4. Security 
  5. Environment of multiple teams 

*DI is not only limited to controllers, any class implements injected interface can use them.
*Web application and Web API both can use same classes in .Net Core.

Some Facts to be noted about ASP.Net Core Web API:
  1. Attribute Routing: Actions automatically called without mentioning action name as routes mentioned above actions.

    [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET api/values
            [HttpGet]
            public ActionResult<IEnumerable<string>> Get()
            {
                return new string[] { "value1", "value2" };
            }

            // GET api/values/5
            [HttpGet("{id}")]
            public ActionResult<string> Get(int id)
            {
                return "value";
            }

            // POST api/values
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }

            // PUT api/values/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }

            // DELETE api/values/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
     
  2. Automatic Model validation: Posted model validated automatically no need to write any code. In case of any issue in validation, it returns with 400.
  3. Binding Source Attributes: 
    1. [FromBody]
    2. [FromForm]
    3. [FromQuery]
    4. [FromHeader]
    5. [FromRoute]
    6. [FromServices]

      // POST api/values
      [HttpPost]
      public void Post([FromBody] string value)
      {
      }
  4. Core Web API supports only Json in response, even if you request some other format type in request header.

    If you want to use XML format in request and response than 
    • You need to install below package from nuget.
      Microsoft.ASPNetCore.Mvc.Formatters.xml
    • Add AddXmlSerializerFormatters() method with AddMvc()
      public void ConfigureServices(IServiceCollection services)
              {
                  services.AddMvc()
                      .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                      .AddXmlSerializerFormatters();
              } 
  5. HttpClient is the class to call and use WebAPI from .Net classes.
  6. Calling WebAPI using client side script

    Add a new item

    function addItem() {
      const item = {
        name: $("#add-name").val(),
        isComplete: false
      };

      $.ajax({
        type: "POST",
        accepts: "application/json",
        url: uri,
        contentType: "application/json",
        data: JSON.stringify(item),
        error: function(jqXHR, textStatus, errorThrown) {
          alert("Something went wrong!");
        },
        success: function(result) {
          getData();
          $("#add-name").val("");
        }
      });
    }

    Update an exiting item 
    $.ajax({
      url: uri + "/" + $("#edit-id").val(),
      type: "PUT",
      accepts: "application/json",
      contentType: "application/json",
      data: JSON.stringify(item),
      success: function(result) {
        getData();
      }
    });

    Delete an item
    $.ajax({
      url: uri + "/" + id,
      type: "DELETE",
      success: function(result) {
        getData();
      }
    });

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...