Sunday, 15 April 2018

Detecting Ajax Requests In ASP.NET MVC 5

Security is one of my major concerns nowadays and it is quite common that someone will try to browse to a particular URL given any chance. To avoid this, we can detect whether the request came from an Ajax request or from a normal browser request.

Within ASP.NET MVC5 applications is quite easy to check if a request is being made via AJAX through the extension named IsAjaxRequest() method that is available on the Request object. The IsAjaxRequest() actually works by simply performing a check for the X-Requested-With header.

The example below will show you how wrap this functionality inside an Action Filter so you can add this feature to any controller you want to perform this check upon.

Creating the Action Filter:

Then just use the attribute in any of the actions you want to perform this operation:

And now, if you try to browse that action from a normal request you will get the following error:

Now you can make your site more secure without worrying about someone inadvertently clicking to  the action.