Adding AjaxOnly Filter in ASP.NET Web API

        Introduction:


                    Currently, ASP.NET MVC 4, ASP.NET Web API and ASP.NET Single Page Application are the hottest topics in ASP.NET community. Specifically, lot of developers loving 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 can only be accessed from Ajax. In this article, I will show you how to implement 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.


5 Comments

Comments have been disabled for this content.