简体   繁体   中英

Asp.net core MVC make action optional in routing

Im trying to manage my routing settings for my projet but I don't understand everything, I want to make some actions or controllers names optional in the url.

For example I have a controller "HomeController" with a "SignIn()" action, I want it to be reachable with the url "/signin" and not "/home/signin".

Same for a controller named "ProjectsController" with an action "Details(int id)", I want it to be reachable with "/projects/348" and not "/projects/details/348".

I didn't modify the default endpoint configuration:

endpoints.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

How can I make some controllers name and actions name optional? And after that will I be able to still use tag helpers for links with asp-controller and asp-action?

I think you have to use route attributes. For example for your SignIn action

    public partial class HomeController : Controller
    {
        [Route("~/signin")]
        public IActionResult SignIn()
        {
            .....
        }
    }

and use the same template for another special actions

and you can have several routes for one action too

        [Route("~/signin")]
        [Route("~/home/signin")]
        public IActionResult SignIn()
        {
            .....
        }

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