0

I have a setup where I use one route with url's on the following format:

www.example.com/friendly-url-1

www.example.com/friendly-url-2

www.example.com/another-friendly-url

The route is defined like this:

routes.MapRoute("FriendlyUrl", "{name}",
             new { controller = "FriendlyUrl", action = "Index", name = UrlParameter.Optional }
         );    

Name is an internal property in my application that lets me look up which controller should be used in a custom ControllerFactory, and change the name of the controller that is created (there is no actual controller called FriendlyUrl).

It works well if I only have one action per controller, but since action isn't part of the route, it always uses the default action. I want to have more than one action, but I'm not able to find a good way for me to write logic that controls which action should be used for each request. Is it possible?

4

2 回答 2

1

If I correctly understand, you have urls in form "www.example.com/friendly-url/name" and want name to determine both controller and action, e.g.

  • "example.com/friendly/foo" would resolve to SomeController and XxxAction
  • "example.com/friendly/boo" would resolve to AnotherController and ZzzAction

I think, the easiest way would be to use custom route handler

public class MyRouteHander : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var values = requestContext.RouteData.Values;
        var token = GetRequestToken(requestContext); 
        switch (token) {
           case "friendly/foo") {
            values["controller"] = "some";
            values["action"] = "xxx";
            break;
           case "friendly/boo") {
            values["controller"] = "another";
            values["action"] = "zzz";
            break;
           ...
        }
        return new MvcHandler(requestContext);
    }
}

and then you register the handler with

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new MyRouteHander();
于 2013-07-02T08:12:53.993 回答
0

You can write dedicate route for your URL's and it will call different action in that case. but if you want to use a expression to route to different actions i don't think you can do it directly by writing route in routeConfig as you need to specify somewhere the mapping of URL Segment to Action which is equivalent to creating dedicated routes in routeConfig

于 2013-07-02T07:32:00.753 回答