Detect ajax request in C#

Easier way to detect whether request is an ajax request

Sometime you need to determine whether your request is standard GET/POST request or Ajax POST/GET http request.

This info is stored in request value isAjax or X-Requested-With. By checking these values of request you can easily determine whether http request is ajax or not.

To make it more reusable you can add this check as an extension method for HttpRequest class.

public static bool IsAjaxRequest(this HttpRequest request)
        {
            if (request["isAjax"] != null)
            {
                return true;
            }
            var page = HttpContext.Current.Handler as Page;
            if (request.HttpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase) && !page.IsPostBack)
            {
                return true;
            }
            if (request != null)
            {
                return (request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));
            }
            return false;
        }
    

You can find attached solution with sample how to apply this approach

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article