2

The goal

Overload the "Index" method to be like myapp.com/Category/SomethingHere/.

The problem

I have CategoryController with Index() method as this:

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

And works normally¹ until I access myapp.com/Category/Cars/ or myapp.com/Category/Sports/.

The response I received when I try to access these URLs is:

Server Error in '/' Application.

The resource cannot be found.

What I've already tried

At App_Start/RouteConfig.cs:

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

But with no success and the problem is the same.

Considerations

Other things I have already tried:

public ActionResult Index(string? categoryName) { }

and

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

Success? No. Visual Studio returns me an error when I use this syntax

The type "string" must be a non-nullable value type in order to use it as parameter "T" in the generic type or method "System.Nullable".

Observations

¹: "Normally" means: if I access myapp.com/Category/, Test is showed for me.

Ambiguous question?

Maybe. Unfortunately, no other answer that I found here — on Stack — worked for me. I have already tried this question by Patrick, this question by Papa Burgundy, this question by Andy Evans and some others.

4

1 回答 1

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 
             }
 );

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

于 2013-06-13T20:55:14.813 回答