How can we restrict access to methods with specific HTTP verbs in C# ASP.NET WebAPI?

CsharpServer Side ProgrammingProgramming

The HTTP verbs comprise a major portion of our “uniform interface” constraint and provide us the action counterpart to the noun-based resource. The primary or mostcommonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently. Of those less-frequent methods, OPTIONS and HEAD are used more often than others.

Action method can be named as HTTP verbs like Get, Post, Put, Patch or Delete. However, we can append any suffix with HTTP verbs for more readability. For example, Get method can be GetAllStudents() or any other name which starts with Get.

Example

public class DemoController : ApiController{
   public IHttpActionResult GetAllStudents(){
      //Retrieves students data
      return Ok();
   }
   public IHttpActionResult Post([FromBody]Student student){
      //Insert student data
      return Ok();
   }
   public IHttpActionResult Put([FromBody]Student student){
      //Update student data
      return Ok();
   }
   public IHttpActionResult Delete(int id){
      //Delete student data
      return Ok();
   }
}

The other way defining Http Verb of an action method instead naming is by using Http Verb Attribute. We can easily restrict access to an ASP.NET Web API method to be called using a specific HTTP method.

Example

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      [HttpGet] //HttpVerb Attribute
      public IHttpActionResult FetchStudentsList(){
         List<Student> students = new List<Student>{
            new Student{
               Id = 1,
               Name = "Mark"
            },
            new Student{
               Id = 2,
               Name = "John"
            }
         };
         return Ok(students);
      }
   }
}

Now let us try to access the above action method using post request.

We could see that when we send a post request to FetchStudentsList action method we getting 405 Method Not Allowed response since it is decorated with [HttpGet] attribute.

raja
Published on 19-Aug-2020 12:18:38
Advertisements