Detecting AJAX Requests in ASP.NET Core

Posted by Anuraj on Saturday, June 3, 2017

ASP.NET Core

This post is about detecting Ajax Requests in ASP.NET Core. In earlier versions of ASP.NET MVC, developers could easily determine whether the request is made via AJAX or not with IsAjaxRequest() method which is part of Request method. In this post I am implementing the similar functionlity in ASP.NET Core.

In this implementation, I will be checking whether the Request object contains header with name X-Requested-With. And here is the extension implementation, which detects whether the request header contains X-Requested-With.

public static class HttpRequestExtensions
{
    private const string RequestedWithHeader = "X-Requested-With";
    private const string XmlHttpRequest = "XMLHttpRequest";

    public static bool IsAjaxRequest(this HttpRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        if (request.Headers != null)
        {
            return request.Headers[RequestedWithHeader] == XmlHttpRequest;
        }

        return false;
    }
}

And here is the AjaxOnly attribute implementation, which you need to add in the action methods.

public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
    {
        return routeContext.HttpContext.Request.IsAjaxRequest();
    }
}

If the selected action method decorated with AjaxOnly attribute and if users try to access without the header, the response will be Not found.

[AjaxOnly]
public IActionResult HelloWorld()
{
    return Json(new { Name = "Anuraj", Email = "anuraj.p@example.com" });
}

Happy Programming :)


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub