.NET Zone is brought to you in partnership with:

Imran is a DZone MVB and is not an employee of DZone and has posted 32 posts at DZone. View Full User Profile

Adding AjaxOnly Filter in ASP.NET Web API

04.01.2012
| 3995 views |
  • submit to reddit

Introduction

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.

Description

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,

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

Summary

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, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)