Search code examples
c#.netasp.net-mvcuser-agentadaptive-design

ASP.NET Mobile Views: Not detecting Firefox Mobile as Mobile


I'm using ASP.NET MVC 5. I render a bunch of .mobile views for some specific scenarios.

I've noticed that the Mozilla Firefox mobile app on Android isn't getting the .mobile version of the rendered view, so it's like ASP.NET isn't detecting that the device is mobile.

The user agent string is:

Mozilla/5.0 (Android; Mobile; rv:39.0) Gecko/39.0 Firefox/39.0

Is there a way I can globally override the mobile detection to force this?


Solution

  • Yes you can, using the DisplayModeProvider in the System.Web.WebPages namespace.

    You can add your own logic to the DisplayModeProvider to determine which view should be rendered.

    If you add this to your startup or application initialization:

    DisplayModeProvider.Instance.Modes
    .Add(new DefaultDisplayMode("Mobile")
                    {
                        ContextCondition = context => {
                            var userAgent = context.GetOverriddenUserAgent();
                            return userAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) > -1
                                   && userAgent.IndexOf("Mobile", StringComparison.OrdinalIgnoreCase) > -1
                                   && userAgent.IndexOf("Firefox", StringComparison.OrdinalIgnoreCase) > -1;
                        }
                    });
    

    This will direct http requests that have "Android", "Mobile" and "Firefox" in the User Agent string to your views suffixed with Mobile.

    Similarly, you can create specific overrides and views for specific devices, i.e. a view for iPhone 4, another view for iPhone 5 etc.. More information can be found here.