MVC4 Force Mobile Site for all requests including Desktop

☆樱花仙子☆ 提交于 2019-12-08 11:08:35

问题


I have created an MVC 4 Internet Application project for both Mobile and Desktop devices. Now I want to just display the Mobile site globally for all browsers.

I've been trying to use the code HttpContext.SetOverriddenBrowser(BrowserOverride.Mobile) to do this, but it doesn't seem to work correctly no matter where I put it.

Currently I can switch from the desktop site to the mobile site using ViewSwitcher but this is impractical as the desktop site isn't yet functional.

public RedirectResult SwitchView(bool mobile, string returnUrl) {
    if (Request.Browser.IsMobileDevice == mobile)
        HttpContext.ClearOverriddenBrowser();
    else
        HttpContext.SetOverriddenBrowser(mobile ? BrowserOverride.Mobile : BrowserOverride.Desktop);

    return Redirect(returnUrl);
}

All of my mobile views are in VIEWNAME.Mobile.cshtml format. Any help would be greatly appreciated, thank-you.


回答1:


I'm maybe a bit late to the party, but I had the same problem like the OP and didn't like Tieson's solution. So I came up with an alternative, that worked great for me.

Add the following code to your projects Global.asax.cs:

protected void Application_BeginRequest()
{
    Request.RequestContext.HttpContext.SetOverriddenBrowser(BrowserOverride.Mobile);
}

This tells ASP.NET on every request, that it's a request of a mobile browser.




回答2:


I suppose a different tack to try would be to manually specify the mobile views when you return the result from the controller action. View() has quite a few overloads (see http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view%28v=vs.100%29.aspx), one of which lets you specify the view to render: return View("index.mobile", model) should work. Once the rest of the app is complete a simple Find+Replace would let you remove the "hack".



来源:https://stackoverflow.com/questions/16080593/mvc4-force-mobile-site-for-all-requests-including-desktop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!