简体   繁体   中英

Routing root request to this controller and action in MVC

I have a URL request in the following format: http://localhost/activate?activationCode=X

I would like this request to be handled in the Home controller, by the Activate action.

I am not sure how to proceed. I have looked at RouteConfig.cs and see the way routes are defined here:

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

But how can I make Home/Activate handle URL's of the following format? http://localhost/activate?activationCode=X

...so as to add a special case where activate proceeding the host name goes to the Home controller, and Activate action?

You need to create a specific route

routes.MapRoute(
    name: "Activate",
    url: "Activate/{id}",
    defaults: new { controller = "Home", action = "Activate", id = UrlParameter.Optional }
);

and place this one before the default route.

In addition if you want http://localhost/activate/X rather than http://localhost/activate?activationCode=X , then change it to

routes.MapRoute(
    name: "Activate",
    url: "Activate/{activationCode}",
    defaults: new { controller = "Home", action = "Activate", activationCode = UrlParameter.Optional }
);

and make the method in HomeController

public ActionResult Activate(string activationCode)

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