Tuesday, March 15, 2011

Why can't ASP.NET MVC URL routing find my controller?

In my Global.asax.cs file in RegisterRoutes method, I put

routes.MapRoute("messages", 
    "Message/{id}", 
    new { controller = "Archive", action = "Message", id = 0 });

Then I created this controller:

namespace TestingApp.Controllers
{
    public class ArchiveController : Controller
    {
        public string Message(int id)
        {
            return "testing: you will receive the message: " + id.ToString();
        }
    }
}

But in my browsser when I go to:

http://.../Message/34

I get a 404.

What else do I need to define so that the routing finds my controller?

From stackoverflow
  • Try defining your specific route before the Default one:

    routes.MapRoute(
        "messages",
        "Message/{id}",
        new { controller = "Archive", action = "Message", id = 0 });
    
    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = "" });
    
  • I think your Message method should return an ActionResult instance:

    public ActionResult Message(int id)
    {
        return new ContentResult {
            Content = "testing: you will receive the message: " + id.ToString()
        };
    }
    
    AnthonyWJones : A controller returning a string is acceptable in ASP.NET-MVC

0 comments:

Post a Comment