MVC4捕获对控制器操作的所有请求

时间:2013-02-05 18:40:32

标签: asp.net-mvc asp.net-mvc-4

我的应用程序需要能够让用户使用foo.com/pubid约定导航到页面,其中pubid是随机生成的字符串,例如“wgwrfwrcwrf”。

我的Home控制器定义了一个Index ActionResult:

    public ActionResult Index(string id)
    {
         //do stuff
    }

当我在我的网站上导航到此操作而未指定ID时,一切都很好。我返回与home关联的视图。这就是bit.ly所做的。我正在尝试在我的应用程序中翻译该ID。

但是,如果我请求诸如foo.com/wgwrfwrcwrf之类的URL,我会收到404.我需要能够捕获此字符串以将其发送到正确的视图。这需要自定义路线吗?

2 个答案:

答案 0 :(得分:0)

routes.MapRoute(
    "id", // Route name
    "{id}", // id route
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
);

答案 1 :(得分:0)

你应该写一个像这样的全能路线......

    routes.MapRoute("catchall", "{*id}", 
                               new {
                                      controller = "Home", 
                                      action = "Index", 
                                      id = UrlParameter.Optional
                                   });

享受:)

相关问题