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.

Community
  • 1
  • 1
Guilherme Oderdenge
  • 4,935
  • 6
  • 61
  • 96

1 Answers1

2

You should have routes like this.

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

Notice that the constraint says first segment has to be exactly "Category". This makes sure default route still gets to handle all other requests. You have to keep the default route to not the break the convention for other controllers. Also make sure default route is mapped last.

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156