加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – ASP.NET MVC 4移动功能

发布时间:2020-12-15 19:33:57 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试新的ASP.NET MVC 4移动功能。我做了一个简单的应用程序只有一个控制器(HomeController)和一个视图(索引)。我还添加了一个移动版本的索引视图。 Views/Home/Index.cshtmlViews/Home/Index.Mobile.cshtml 当在桌面浏览器中启动应用程序时,正常视图
我正在尝试新的ASP.NET MVC 4移动功能。我做了一个简单的应用程序只有一个控制器(HomeController)和一个视图(索引)。我还添加了一个移动版本的索引视图。
Views/Home/Index.cshtml
Views/Home/Index.Mobile.cshtml

当在桌面浏览器中启动应用程序时,正常视图显示为预期,但是当我在Opera Mobile Emulator作为三星Galaxy S启动应用程序时,我仍然获得常规视图,而不是移动版本。

从模拟器发送的用户代理字符串如下所示:

Opera/9.80 (Windows NT 6.1; Opera Mobi/23731; U; en) Presto/2.9.201 Version/11.50

任何想法为什么这不工作?

更新
感谢@nemesv我能够解决问题,这里是我目前的解决方案,希望它会涵盖大多数移动场景。

public class MobileDisplayMode : DefaultDisplayMode
{
    private readonly StringCollection _useragenStringPartialIdentifiers = new StringCollection
    {
        "Android","Mobile","Opera Mobi","Samsung","HTC","Nokia","Ericsson","SonyEricsson","iPhone"
    };

    public MobileDisplayMode() : base("Mobile")
    {
        ContextCondition = (context => IsMobile(context.GetOverriddenUserAgent()));
    }

    private bool IsMobile(string useragentString)
    {
        return _useragenStringPartialIdentifiers.Cast<string>()
                    .Any(val => useragentString.IndexOf(val,StringComparison.InvariantCultureIgnoreCase) >= 0);
    }
}

和我Global.asax

DisplayModeProvider.Instance.Modes.Insert(0,new MobileDisplayMode());

解决方法

ASP.Net(实际上是HttpBrowserCapabilitiesBase类)不能识别Opera Mobile Emulator作为移动浏览器。

您可以在任何控制器操作中检查:HttpContext.Request.Browser.IsMobileDevice将为Opera Mobile浏览器返回false。

因为内置的DefaultDisplayMode使用以下方法来检查移动浏览器,您需要注册您的自定义DisplayMode,它正确地识别Opera Mobile。

为此,您需要将其添加到Global.asax Application_Start:

DisplayModeProvider.Instance.Modes.Insert(0,new DefaultDisplayMode("Mobile")
{
    ContextCondition = (context => context.GetOverriddenUserAgent()
        .IndexOf("Opera Mobi",StringComparison.OrdinalIgnoreCase) >= 0)
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读