开发者

How can i create a route that returns a URL without controller reference in ASP.NET MVC

I have a controller call DefaultController. Inside this controller i have views for what wo开发者_JAVA技巧uld be the equivalent of static pages.

The URLs look like www.site.com/Default/PageName

Is it possible to create a route that would format these URL like:

www.site.com/PageName

I want to avoid creating controllers for each of these. An alternative would be to create .aspx pages in the root but can i create routes for these pages ie:

www.site.com/PageName.aspx becomes www.site.com/PageName ?

Thanks!


You can create explicit route for the PageName action on the DefaultController like this:

routes.MapRoute(
    "PageName",
    "pagename",
    new { controller = "DefaultController", action = "PageName" }
);

You have to put this route before the default MVC route. The biggest drawback for this approach is that you have to create one route per static page.

An alternative approach would be to add an additional route after the default MVC route:

routes.MapRoute(
    "DefaultController",
    "{page}/{*path}",
    new { controller = "DefaultController", action = "{page}" }
);

The drawback for this approach is that this rule would be handling all the URLs, even those that would normally return 404.


First approach

Create a route that catches actions:

routes.MapRoute(
    "Catcher1",
    "{action}",
    new { controller = "Default", action = string.Empty });

But this means you'd have to create just as many controller actions on your default controller.

Second approach

If you'd like to avoid that as well and have just one controller+action instead, write a route this way:

routes.MapRoute(
    "Catcher2",
    "{path}",
    new { controller = "Default", action = "PageName", path = string.Emtpy },
    new { path = @"[a-zA-Z0-9]+" });

This route also defines a route constraint so it will catch only those routes, that actually have something in first route segment. You can define this constraint to only catch those requests that you need (ie. path = "Result|Search|Whatever")

then your DefaultController would have something like this:

public ActionResult PageName(string path)
{
    // code goes here
}

Second approach seems very feasible, but I wouldn't recommend it because all logic would have to go through this controller action (for these kind of requests). It would be better to separate these actions into logical ones. Those that actually do the same thing (so they wouldn't have a bunch of switch statements or similar) would be defined with separate routes (if they couldn't be done using a single one).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜