开发者

ASP.NET MVC route returning 404 without action

I am working on a very simple application, using MVC2 Preview 1.

I have a controller named ContentController. My problem is t开发者_开发知识库hat /Content/Index works correctly, but /Content/ returns a 404. I am running the application on the Studio Development Server.

Tested with RouteDebugger but /Content/ returns a 404, and does not display any debugging information.

I have not changed the routing code:

       routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

This is my controller:

public class ContentController : Controller
{
    IRepository _repo = new SimpleRepository("db", SimpleRepositoryOptions.RunMigrations);

    public ActionResult Index()
    {
        var content = _repo.GetPaged<Content>(0, 20);
        return View(content);
    }


It's a shot in the dark, but do you have a directory named /Content/ as well?


/Content is a controller, which is basically just a collection of actions. ASP.NET MVC needs to know WHICH action you want to run, so by leaving out the action asp.net mvc doesn't know what action to return and gives a 404.

You can tell it a default either by adding a route:

eg:

routes.MapRoute("ContentDefault", "Content", new {controller = "Content", action = "Index"});

The attributes are defined as follows:

'ContentDefault`: Name of the Route (must be unique in your routing table)

Content: The URL segment (try changing this to 'Content/Much/Longer/URL' and then go to http://localhost/Content/Much/Longer/URL to see how this works)

new {controller=.., action=...}: which controller/action combo to run for this route.

You could also override HandleUnknownAction in your controller:

    protected override void HandleUnknownAction(string actionName)
    {
         return RedirectToAction("index");
    }

Oh and incidentally, an extra piece of advice about routing.... if you add something to the route in braces { } these will be passed to the action as an attribute.

e.g. /Content/Much/Longer/Url/{page}

so the URL http://localhost/Content/Much/Longer/Url/999

will pass the 999 into your action, as the page attribute

public ActionResult Index(int Page) { }

I love MVC - never going back to WebForms - this is how web development should be!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜