简体   繁体   中英

MVC Action as singleroute without controller

I've some controllers where i want to show only the action as route. For start i get Home/Start . I like to show only /Start . For Contact as well. Is it only changeable through the routeconfig or is there an attribute?

public class HomeController : Controller
{
    public ActionResult Start()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

    public ActionResult Impress()
    {
        return View();
    }
}

Route config is the only way to do this, here's how

First, define all the non-home controllers routes like this:

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

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

Then after all those, define the default route like so:

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

Use AttributeRouting.

You just have to put an attribute with the name of the Action before the action :

    [HttpGet]
    [Route("Get")]
    public ViewAction Get(long id)
    {
        return;
    }

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