Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC3 路由之不同区域的相同 URL

2024年02月23日14开发

我的 MVC3 项目有一个名为 Mobile 的区域。以下是从桌面浏览器和移动浏览器访问我的网站时的行为:

  1. 桌面浏览器:URL 保留为 mydomain.com,默认桌面主页正确显示。

  2. 移动 (iPhone) 浏览器:URL 更改为 mydomain.com/Mobile/Home,移动主页正确显示。

无论是从桌面浏览器还是移动浏览器查看,我都希望 URL 保留为 mydomain.com。我该如何实现?

请您参考如下方法:

尝试为移动设备使用 ActionName 过滤器和自定义操作方法选择器。 示例(从“Pro ASP.NET MVC 2”一书第 351 页复制):

- In Controller define 2 function for desktop & iPhone, they have the same ActionName 
 
    [iPhone] 
    [ActionName("Index")]  
    public ActionResult Index_iPhone() { /* Logic for iPhones goes here */ }      
    [ActionName("Index")] 
    public ActionResult Index_PC() { /* Logic for other devices goes here */ } 
 
- Define [iPhone] action method selector:            
    public class iPhoneAttribute : ActionMethodSelectorAttribute  
        {  
            public override bool IsValidForRequest(ControllerContext controllerContext,   
                                                   MethodInfo methodInfo)  
            {  
                var userAgent = controllerContext.HttpContext.Request.UserAgent;  
                return userAgent != null && userAgent.Contains("iPhone");  
            }  
        }