简体   繁体   中英

How do I mix short URLs and regular URLs in ASP.NET MVC?

I have a site with the normal, default route and several controllers. I would like to distribute "short URL" links that can link back to the home/index action. For example, I can do

  • /MySite - takes you to Home/Index as default
  • /MySite/SomeController/SomeAction - takes you to the specified controller/action as default

but I would also like to do:

/MySite/SomeID - takes you to Home/Index with the id param supplied.

I can add a "shortUrl" route and distribute a url like "/MySite/ShortUrl/SomeID", but is there any other way to use an "id-only" url like the one above?

The problem you've got with doing something like this is that the following would then be ambiguous:

/MySite/SomeID
/MySite/SomeController

How do you expect to be able to differentiate between the two? If you don't mind the second being impossible (ie you are happy always specifying an action when you specify a controller), you could try something like this:

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

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

Requesting /MySite/SomeID should then take you to the same action as MySite/Home/Index/SomeID .

If you need to be able to specify either and ID or a controller (with default action), you could do something like the following (also using the above routing):

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        // If the ID represents something, show that something.
        if (IdMatchesSomeResource(id))
        {
            // Do something
            return View();
        }
        // Otherwise, treat it as a request for a controller.
        else
        {
            return RedirectToAction("Index", id);
        }
    }
}

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