ASP.Net Core: Is the current request from Ajax?


Here is a handy extension method for ASP.NET Core to determine if the request being made is an Ajax request. Additionally it can check if the Ajax request is a POST or GET.

Extension Method

/// <summary>
/// If a request is an Ajax request.
/// </summary>
/// <param name="request"></param>
/// <param name="httpVerb"></param>
public static bool IsAjax(this HttpRequest? request, string httpVerb = "")
{
    if (request == null)
    {
        return false;
    }

    if (!string.IsNullOrEmpty(httpVerb))
    {
        if (request.Method.ToLower() != httpVerb.ToLower())
        {
            return false;
        }
    }

    return request.Headers["X-Requested-With"] == "XMLHttpRequest";
}

Usage

Note: This requires access to the HttpContext.

if (this.HttpContext.Request.IsAjax("GET"))
{
    // Do something
}