Url route with id without controller

Viewed 344

I have a question, I want to set an url route like so
https://www.niris.si/1234 -> this being the id instead of https://www.niris.si/ControllerName/ActionName/1234

Is this even possible?

I have tried with the code bellow:

 endpoints.MapControllerRoute(
                name: "Name",
                pattern: "/{id?}",
                defaults: new { Controller="RandomController", action = "Index" });

But I can only get it to work like so: https://www.niris.si/ControllerName/1234

with this piece of code:

endpoints.MapControllerRoute(
                name: "Name",
                pattern: "RandomController/{id?}",
                defaults: new { Controller="RandomController", action = "Index" });

In this case I got rid of the action name but not the controller name.

Thanks for your help and advice, kind regards

1 Answers

Try map the route like below:

// For ASP.NET Core 
endpoints.MapControllerRoute("Random", pattern: "{id?}", new { Controller = "Random", action = "Index" });

// For ASP.NET MVC
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{id}",
            defaults: new { controller = "Random", action = "Index", id = UrlParameter.Optional }
        );
    }
}
// ASP.NET Core MVC
public class RandomController : Controller
{        
    public IActionResult Index(int? id)
    {
        // TODO: Your the action code here ...

        return View();
    }
    ...
}

// ASP.NET MVC
public class RandomController : Controller
{        
    public ActionResult Index(int? id)
    {
        // TODO: Your the action code here ...

        return View();
    }
    ...
}
Related