Adding AjaxOnly Filter in ASP.NET Web API

DZone 's Guide to

Adding AjaxOnly Filter in ASP.NET Web API

· ·
Free Resource


Currently, ASP.NET MVC 4, ASP.NET Web API and ASP.NET Single Page Application are the hottest topics in the ASP.NET community. Specifically, lots of developers love the inclusion of ASP.NET Web API in ASP.NET MVC. ASP.NET Web API makes it very simple to build HTTP RESTful services, which can be easily consumed from desktop/mobile browsers, silverlight/flash applications and many different types of clients. Client side Ajax may be a very important consumer for various service providers. Sometimes, some HTTP service providers may need some (or all) of thier services only accessed from Ajax. In this article, I will show you how to implement the AjaxOnly filter in ASP.NET Web API application.


First of all you need to create a new ASP.NET MVC 4 (Web API) application. Then, create a new AjaxOnly.cs file and add the following lines in this file,

    public class AjaxOnlyAttribute : System.Web.Http.Filters.ActionFilterAttribute
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
            var request = actionContext.Request;
            var headers = request.Headers;
            if (!headers.Contains("X-Requested-With") || headers.GetValues("X-Requested-With").FirstOrDefault() != "XMLHttpRequest")
                actionContext.Response = request.CreateResponse(HttpStatusCode.NotFound);
This is an action filter which simply checks X-Requested-With header in request with value XMLHttpRequest. If X-Requested-With header is not presant in request or this header value is not  XMLHttpRequest then the filter will return 404(NotFound) response to the client. 

Now just register this filter,

        public string GET(string input)
You can also register this filter globally, if your Web API application is only targeted for Ajax consumer.


ASP.NET WEB API provide a framework for building RESTful services. Sometimes, you may need your certain API services can only be accessed from Ajax. In this article, I showed you how to add AjaxOnly action filter in ASP.NET Web API. Hopefully you will enjoy this article too.

Published at DZone with permission of Imran Baloch , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}