开发者

Id in the beginning of the Route in MVC

I have a situation where I want a route in my application so that the 开发者_JAVA技巧application's index method can recognize this http://www.website.com/ID

and also, http://www.website.com/Controller/Action should also work.

The problem is that, when I set up the route corresponding to the first URL, the route for the second URL does not work (even if I set up a separate route for that).

Please tell me what am I doing wrong here...


Does the ID value have some distinguishing characteristic that would allow you to tell the difference between it and a controller name? For example, is it numeric? If so, you can set up a constraint on the first route so that it only matches ids. This would allow other requests to fall through to the second (default) route.

routes.MapRoute(
    "IdRoute",
    "{id}",
    new { controller = "home", action = "get" },
    new { id = "\d+" } // match ids that consist of 1 or more digits
);

routes.MapRoute(
    "Default",
    new { controller = "home", action = "index", id = UrlParameter.Optional }
);


The following should work:

routes.MapRoute(
    "DefaultWithID",
    "{id}",
    new { controller = "Home", action = "Index" }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Assuming:

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        return View();
    }
}

Both: /123 and /Home/Index/123 work fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜