ASP.NET MVC 4.0 has two great features: One is Display Mode allows you to create mobile-specific and desktop-specific views and Second is Web API platform for building RESTful applications. Sometimes, You might need to return different data or perform different operations for desktop and mobile request. This article explains how to implement separate actions for mobile request keeping same URL format in Web API.

1. In Visual Studio, Select File > New Project > ASP.NET MVC 4 Web Application > Enter name > OK


2. Select ‘Web API‘ > View Engine: ‘Razor‘ > OK


3. You’ll get default ValuesController. When you access <your app url>/api/Values, the array of string value1, value2 is returned.


To create separate action for mobile request, We are going to create separate controller having ‘Mobile‘ suffix.


Right Click on ‘Controllers‘ folder > Add Controller > Give Name ‘ValuesMobileController‘ > Template: ‘API Controller with empty read/write actions‘ > Add


To differentiate both controllers, replace value1, value2 to mobile-value1, mobile-value2 in get method.


4. Now our object is to call action of Mobile controller when request comes from mobile device.


In Global.asax:


default api route:


routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );

Change it to


routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           ).RouteHandler = new MyRouteHandler();

and add following class:


public class MyRouteHandler : HttpControllerRouteHandler
   {
       protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
       {
           //Check whether request comes from mobile browser
           if (requestContext.HttpContext.Request.Browser.IsMobileDevice)
           {
               string controller = requestContext.RouteData.Values["controller"].ToString();
               requestContext.RouteData.Values["controller"] = controller + "Mobile";
           }
           return new MyHttpControllerHandler(requestContext.RouteData);
       }
   }

   public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
   {
       public MyHttpControllerHandler(RouteData routeData)
           : base(routeData)
       {
       }
   }

You have to import following namespaces:


using System.Web.Http.WebHost;
using System.Web.SessionState;

In this RouteHandler, Request.Browser.IsMobileDevice checks whether request comes from mobile browser and change controller name with ‘Mobile‘ suffix.

Now run app on browser, For testing, You can change user-agent to iPhone with user agent switcher Firefox add-on and open same URL. you’ll get mobile-value1 and mobile-value2.



Hope it helps