Detect ajax request in C#

Easier way to detect whether request is an ajax request

  • Share

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

  • Share

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.

Comments for this article

comments powered by Disqus