Create Exception Filter to Handle Unhandled Exceptions in C# ASP.NET WebAPI

Nizamuddin Siddiqui
Updated on 19-Aug-2020 12:37:03

468 Views

An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface. The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.Below is a filter that converts NotFiniteNumberException exceptions into HTTP status code 416, Requested Range Not Satisfiable.ExceptionFilterAttribute −Exampleusing System; using System.Net; using System.Net.Http; using System.Web.Http.Filters; namespace DemoWebApplication.Controllers{    public class ExceptionAttribute : ExceptionFilterAttribute{       public override void OnException(HttpActionExecutedContext ... Read More

Versioning with QueryString Parameter in C# ASP.NET WebAPI

Nizamuddin Siddiqui
Updated on 19-Aug-2020 12:32:59

468 Views

The DefaultHttpControllerSelector class in web api is responsible for selecting the appropriate controller action method that we send in the URI.Say we have to implement versioning in the query string like belowv=1 StudentsV1Controller (Version 1) v=2 StudentsV2Controller (Version 2)If we pass the versioning information in the query string like http://localhost:58174/api/student?v=1 will result in 404 Not Found error response because the SelectController() method which is present in DefaultHttpControllerSelector will look for the StudentsController but we have only StudentsV1Controller and StudentsV2Controller.To handle this case, we should add our own CustomControllerSelector which implements the DefaultHttpControllerSelector class.CustomControllerSelector −Exampleusing System.Net.Http; using System.Web; using System.Web.Http; using ... Read More

Web API Versioning with URI in C# ASP.NET Web API

Nizamuddin Siddiqui
Updated on 19-Aug-2020 12:26:20

764 Views

Once a Web API service is made public, different client applications start using our Web API services. As the business grows and requirements change, we may have to change the services as well, but the changes to the services should be done in way that does not break any existing client applications.This is when Web API versioning helps. We keep the existing services as is, so we are not breaking the existing client applications, and develop a new version of the service that new client applications can start using.One of the option to implement versioning is by using URI. Below ... Read More

Restrict Access to Methods with Specific HTTP Verbs in C# ASP.NET Web API

Nizamuddin Siddiqui
Updated on 19-Aug-2020 12:19:50

2K+ Views

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 ... Read More

Assign Alias Names for Action Method in C# ASP.NET WebAPI

Nizamuddin Siddiqui
Updated on 19-Aug-2020 12:14:16

3K+ Views

A public method in a controller is called an Action method. Let us consider an example where DemoController class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete.Examplepublic class DemoController : ApiController{    public IHttpActionResult Get(){       //Some Operation       return Ok();    }    public IHttpActionResult Post([FromUri]int id){       //Some Operation       return Ok();    }    public IHttpActionResult Put([FromUri]int id){       //Some Operation       return Ok();    }    public IHttpActionResult Delete(int id){   ... Read More

Different Types of Filters in C# ASP.NET WebAPI

Nizamuddin Siddiqui
Updated on 19-Aug-2020 12:09:58

13K+ Views

Filters are used to inject extra logic at the different levels of WebApi Framework request processing. Filters provide a way for cross-cutting concerns (logging, authorization, and caching). Filters can be applied to an action method or controller in a declarative or programmatic way. Below are the types of filters in Web API C#.Authentication Filter −An authentication filter helps us to authenticate the user detail. In the authentication filter, we write the logic for checking user authenticity.Authorization Filter −Authorization Filters are responsible for checking User Access. They implement the IAuthorizationFilterinterface in the framework.Action Filter −Action filters are used to add extra ... Read More

Resolve CORS Issue in C# ASP.NET Web API

Nizamuddin Siddiqui
Updated on 19-Aug-2020 11:57:44

7K+ Views

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.For example, let us consider an application which is having its front end (UI) and back end (Service). Say the front-end is served from https://demodomain-ui.com and the backend is served from from https://demodomain-service.com/api. If an end user tries to access the application, for security ... Read More

Return Custom Result Type from Action Method in C# ASP.NET Web API

Nizamuddin Siddiqui
Updated on 19-Aug-2020 11:54:42

1K+ Views

We can create our own custom class as a result type by implementing IHttpActionResult interface. IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance.public interface IHttpActionResult {    Task ExecuteAsync(CancellationToken    cancellationToken); }If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.ExampleTo have our own custom result we must create a class that implements IHttpActionResult interface.using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace DemoWebApplication.Controllers{    public class CustomResult : IHttpActionResult{       string _value;       HttpRequestMessage _request; ... Read More

Find the Index of Last Element Reduced to Zero in Python

Arnab Chakraborty
Updated on 19-Aug-2020 11:52:28

168 Views

Suppose we have an array A with n numbers and another input K, we have to find the index which will be the last to be reduced to zero after performing a given operation. The operation is explained as follows −Starting from A[0] to A[N – 1], update each element as A[i] = A[i] – K. Now, if A[i] < K then put A[i] = 0 and no further operation will be done on A[i] once it is 0.We have to repeat the operation until all of the elements are reduced to 0. And return the index which will be ... Read More

Return Types of a Controller Action in C# ASP.NET Web API

Nizamuddin Siddiqui
Updated on 19-Aug-2020 11:52:00

8K+ Views

The Web API action method can have following return types.VoidPrimitive Type/Complex TypeHttpResponseMessageIHttpActionResultVoid −It's not necessary that all action methods must return something. It can have void return type.Exampleusing DemoWebApplication.Models using System.Web.Http; namespace DemoWebApplication.Controllers{    public class DemoController : ApiController{       public void Get([FromBody] Student student){          //Some Operation       }    } }The action method with void return type will return 204 No Content response.Primitive Type/Complex Type −The action method can return primitive type like int, string or complex type like List etc.Exampleusing DemoWebApplication.Models; using System.Collections.Generic; using System.Web.Http; namespace DemoWebApplication.Controllers{    public class ... Read More

Advertisements