控制器的重载索引方法

时间:2013-06-13 20:45:49

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

目标

将“索引”方法重载为myapp.com/Category/SomethingHere/

问题

我有CategoryController Index()方法:

//
// GET: /Category/
public ActionResult Index(string categoryName)
{
    if (categoryName != null)
        return View(categoryName);
    else
    {
        return Content("Test");
    }
}

在我访问myapp.com/Category/Cars/myapp.com/Category/Sports/之前正常工作¹。

我尝试访问这些网址时收到的回复是:

  应用程序中的服务器错误。

     

无法找到资源。

我已经尝试了什么

App_Start/RouteConfig.cs

routes.MapRoute(
     name: "CategoriesMapping",
     url: "{controller}/{categoryName}",
     defaults: 
         new { controller = "Categoria", action = "Index", 
                     categoryName = URLParameters.Optional 
             }
 );

但没有成功,问题也是一样。

考虑

我已经尝试过的其他事情:

public ActionResult Index(string? categoryName) { }

public ActionResult Index(Nullable<string> categoryName) { }

成功?不会。当我使用这种语法时,Visual Studio会给我一个错误

  

“string”类型必须是非可空值类型才能在泛型类型或方法“System.Nullable”中将其用作参数“T”。

观察

¹:“正常”表示:如果我访问myapp.com/Category/,则会显示Test

含糊不清的问题?

也许。不幸的是,我在这里找到的其他答案 - 在Stack上 - 对我有用。我已经尝试了this question by Patrickthis question by Papa Burgundythis question by Andy Evans和其他一些。

1 个答案:

答案 0 :(得分:2)

你应该有这样的路线。

routes.MapRoute(
     name: "CategoriesMapping",
     url: "Category/{categoryName}",
     defaults: 
         new { controller = "Categoria", action = "Index", 
                     categoryName = URLParameters.Optional 
             }
 );

routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: 
         new { controller = "Home", action = "Index", 
                     id = URLParameters.Optional 
             }
 );

请注意,约束表示第一段必须完全是“类别”。这可以确保默认路由仍然可以处理所有其他请求。您必须保持默认路由不破坏其他控制器的约定。还要确保最后映射默认路由。