简体   繁体   中英

How to map a route for specific action in C# ASP.NET MVC3?

I need your help, I have no experience how route works.

Now, I have the following urls:

http://website.com/controller1/action1
http://website.com/controller1/action2

The question, how to route to another url for http://website.com/controller1/action1 without affecting the url to http://website.com/controller1/action2

Means:

When access http://website.com/controller1/action1 , I want to show url: http://website.com/shortcut , but for http://website.com/controller1/action2 to show same as http://website.com/controller1/action2 .

It is possible ?

You can add route like to routeCollection in file Global.aspx add to method RegisterRoutes

routes.MapRoute(
    name: "shortcut",
    url: "shortcut",
    defaults: new { controller = "controller1", action = "action1" }
);

The default route in a new ASP.NET MVC 3 application will handle your first two requests, but you may be confused about the naming convention. For example, if you have a controller class named HomeController and an action named action1 inside it, the default handling of that route would be /Home/action1 .

To handle /controller1/action1 and /controller1/action2 , you would need to literally name your controller class controller1Controller and add two actions eg

public class controller1Controller : Controller
{
    public ActionResult action1()
    {
        return View();
    }
    public ActionResult action2()
    {
        return View();
    }
}

To handle your /shortcut route, you can use what Satpal suggested as long as it's defined above the default route. The more specific the route, the earlier in your route definitions it needs to appear eg

routes.MapRoute(
    name: "nameOfShortcutRoute",
    url: "shortcut",
    defaults: new { controller = "controller1", action = "action1" }
);

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

Check out this link for a good Routing tutorial http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM