Showing posts with label ASP.NET Web API. Show all posts
Showing posts with label ASP.NET Web API. Show all posts

Tuesday, August 27, 2019

ASP.NET Web API Action Filter with parameters

Bascailly Web API Action Filter is used to add extra logic before or after action method execute, it could be used for authentication, authorization and logging.


Pass the single parameter to Action Filters:

Here is a custom action filter, which is used to authorize the request based on supplied token and accepts single value for Role property

Custom Action Filter:

public class RestrictedAction : ActionFilterAttribute
    {
        public string Role { get; set; }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuthorized = false;

            IEnumerable<string> values;
            var areHeadersPresent = actionContext.Request.Headers.TryGetValues("X_API_Token", out values);
            ClientData client;

            if (areHeadersPresent)
            {
                client = ClientHelper.GetClient(values.FirstOrDefault());
                if(client.Role == Role)
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Unauthorized Access");
            }

            base.OnActionExecuting(actionContext);
        }
    }


Web API Controller:

        [HttpPost]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
        [RestrictedAction(Role="Admin")]
        public IHttpActionResult SaveOrder(int orderNumber)
        {
            Order order = _orderEngine.SaveOrder(orderNumber);
            if (order == null)
            {
                return BadRequest("Not able to Create a Order");
            }
            return Ok(order);
        }


Pass the multiple parameters to Action Filters:

Here is a custom action filter which accepts collections of values for Role property and error message string

Custom Action Filter:

  public class RestrictedAction : ActionFilterAttribute
    {
        public [] string Role { get; set; }

   public string ErrorMessage { get; set; }

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuthorized = false;

            IEnumerable<string> values;
            var areHeadersPresent = actionContext.Request.Headers.TryGetValues("X_API_Token", out values);
            ClientData client;

            if (areHeadersPresent)
            {
                client = ClientHelper.GetClient(values.FirstOrDefault());
                if(client.Role == Role)
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, ErrorMessage);
            }

            base.OnActionExecuting(actionContext);
        }
    }

Web API Controller:

        [HttpPost]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
   [RestrictedAction(Role= new string[] { "Admin", "IT" },ErrorMessage= "Unauthorized Access")]       
public IHttpActionResult SaveOrder(int orderNumber)
        {
            Order order = _orderEngine.SaveOrder(orderNumber);
            if (order == null)
            {
                return BadRequest("Not able to Create an Order");
            }
            return Ok(order);
        }

ASP.NET Web API Action Filter


Web API Action Filter is used to add extra logic before or after action method execute, it could be used for authentication, authorization and logging.

Web API Action filter is used as attribute which can be used for action method, Web API controller or for whole application.

WEB API Action Filter


For more information about The Lifecycle of an ASP.NET Web API


ASP.NET Framework provides the ActionFilterAttribute abstract class to implement own custom action filter.

ActionFilterAttribute abstract class has the following methods, which you can override

  1. OnActionExecuting – This method is called before a controller action is executed.
  2. OnActionExecuted – This method is called after a controller action is executed.

Both methods have HTTPActionContext object reference and with help of httpActionContext object we can easily get the current HTTP request object and be able to read http request information like header, request URL, data and requested user information.

Here is an example to create a custom action filter to allow only specific role to access action method.

public class RestrictedAction : ActionFilterAttribute

    {
public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuthorized = false;
            IEnumerable<string> values;
            var areHeadersPresent = actionContext.Request.Headers.TryGetValues("X_API_Token", out values);

            ClientData client;

            if (areHeadersPresent)
            {
                client = ClientHelper.GetClient(values.FirstOrDefault());

                if(client.Role == "Admin")
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Unauthorized Access");
            }

            base.OnActionExecuting(actionContext);
   }
   }
  

In Action Filter, we are reading API Token from HTTP request’s header and if specific header presents, then it calls the GetClient method of ClientHelper class to get client information based on passed token.

If the role of current client is not admin, we will reject request and throw Forbidden HTTP Response

Action Filter used for specific Action Method:

If we want to put restriction on specific method, simply apply RestrictedAction attribute to method.

Only Admin Role use can able to Call the SaveOrder action to create a new order, for other roles, API will rejects request.

public class OrderController : ApiController
    {
        IOrderEngine _orderEngine;
        public OrderController(IOrderEngine orderEngine)
        {  _orderEngine = orderEngine; }

        [HttpGet]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
        public IHttpActionResult GetOrder(int orderNumber)
        {
            Order order = _orderEngine.GetOrderByNumber(orderNumber);
            if(order == null)
            {
                return NotFound();
            }
            return Ok(order);
        }

   [HttpPost]
   [Route("api/Order")]
   [ResponseType(typeof(Order))]
        [RestrictedAction]
        public IHttpActionResult SaveOrder(Order order)
        {
            Order order = _orderEngine.SaveOrder(order);
            if (order == null)
            {
                return BadRequest("Not able to Create an Order");
            }
            return Ok(order);
    }
    }

Action Filter used for all methods of Web API Controller:

If we want to put restriction on specific web API controller, simply apply attribute to web api controller class

Only Admin Role use can able to call any action method of this OrderController API, for other roles, API will rejects request.


       [RestrictedAction]
public class OrderController : ApiController
    {
        IOrderEngine _orderEngine;
        public OrderController(IOrderEngine orderEngine)
        {  _orderEngine = orderEngine; }

        [HttpGet]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
        public IHttpActionResult GetOrder(int orderNumber)
        {
            Order order = _orderEngine.GetOrderByNumber(orderNumber);
            if(order == null)
            {
                return NotFound();
            }
            return Ok(order);
        }
    }


Action Filter used for all Web API Controllers:

If we want to put restriction on all web API controllers in your application, simply add below setting in web api config file

Only Admin Role use can able to call any API’s method of this web api application, for other roles, API will rejects request.

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Filters.Add(new RestrictedAction());           
          
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Tuesday, July 16, 2019

ASP.NET Web API : HTTP status code standard of restful API

While designing the restful API, we need to make sure that API should always return the right and consistence HTTP status Code and without consistent HTTP status codes, customers will not know the difference between success or failure without parsing the response body.

HTTP standard provides almost 70 status codes to describe the response status and you can use below HTTP status code for restful API.

200 – OK
204 – OK – No Content
400 – Bad Request
401 – Unauthorized
404 – Resource Not Found
500 – Internal Server Error
503 – Service is not available

HTTP – GET (Resource Inquiry):


HTTP GET  Sequence Diagram
HTTP GET  Sequence Diagram


The above sequence diagram explain how the HTTP request is being processed and returns the HTTP status code.

There are the possible scenarios for processing of the HTTP GET request.

1.    Scenario :   If request resource is found, Returns HTTP – 200 OK with Resource data

HTTP GET 200 OK

2.    Scenario :  If request resource is not available, return HTTP – 404 Resource Not Found  – with message “Resource is not available

HTTP GET 404 Resource Not Found
           
3.    Scenario:       Any Validation Error/invalid input – returns HTTP – 400 Bad Request with validation or error message.

             
HTTP GET 400 BAD REQUEST


HTTP – POST (Resource Creation) 

HTTP POST Sequence Diagram
HTTP POST Sequence Diagram
The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

There are the possible scenarios for processing of the HTTP POST request.

1.    Scenario:   If requested resource is successfully created, Returns HTTP – 201 OK with Newly created Resource data

HTTP POST 201 OK
2.    Scenario:

If request resource is already found or duplicate resource, returns – returns HTTP – 400 Bad Request with validation message

                                                                               OR

·              Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message

HTTP POST 400 BAD REQUEST
  
   HTTP – PUT (Resource Update)

HTTP PUT Sequence Diagram
HTTP PUT Sequence Diagram

The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

There are the possible scenarios for processing of the HTTP PUT request.

1.    Scenario:   Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message
           
HTTP PUT 400 BAD REQUEST


2.    Scenario:  If request resource is not available, return HTTP – 404 Resource Not Found  – with message “Resource is not available


In this scenario, if resource is not available, many architect prefer to create new resource and returns HTTP – 201 OK with newly created resource data

HTTP PUT 201 OK
        
3.    Scenario:  If request resource is available and successfully updated, Returns HTTP – 200 OK with updated Resource data
     

HTTP PUT 200 OK


HTTP – PATCH (Partially Resource Update)

 
HTTP PATCH Sequence Diagram
HTTP PATCH Sequence Diagram


The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

There are the possible scenarios for processing of the HTTP PATCH request.

1.    Scenario : If request resource is available and successfully updated , Returns HTTP – 200 OK with updated Resource data

HTTP PATCH 200 OK
         

2.    Scenario :  Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message

HTTP PATCH 400 BAD REQUEST
                                                         
3.    Scenario :  If request resource is not available, return HTTP – 404 Resource Not Found  – with message “Resource is not available
                


HTTP – DELETE (Delete Resource)

HTTP DELETE Sequence Diagram
HTTP DELETE Sequence Diagram

The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

There are the possible scenarios for processing of the HTTP DELETE request.

1.    Scenario : If request resource is available and successfully deleted, Returns HTTP – 200 OK 

HTTP DELETE 200 OK


2.     Scenario :  Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message


HTTP DELETE 400 BAD REQUEST

3.    Scenario :  If request resource is not available, return HTTP – 404 Resource Not Found  – with message “Resource is not available



Note: In some scenario, requested URI is not matching with any API URI., then by default Web API/IIS returns HTTP – 404 - with message “HTTP resource was found that matches the request URI”

References:
 
Thanks for Visiting!

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...