LP13 LP13 - 1 month ago 10
ASP.NET (C#) Question

How to set routes in asp.net core application

i have asp.net core application. In my application the default route is set to

Home/Index/id


I have one more controller name
Document


public class DocumentController : Controller
{
public IActionResult Index(int? id)
{
// id may be null. Do something with id here
return View();
}

public IActionResult Detail(int id)
{
return View();
}
}


in startp.cs i have setup my route as below

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");

routes.MapRoute(
name: "document",
template: "Document/{action}/{id?}",
defaults: new { controller = "Document", action = "Index" });

});


i can browse the document view as
http://localhost:40004/Document
or
http://localhost:40004/Document?id=1234


however i want the following routes to be valid

http://localhost:40004/Document/1234


http://localhost:40004/Document?id=1234


http://localhost:40004/Document/Details/1234


http://localhost:40004/Document/Details?id=1234


What should be my route configuration in startup.cs?

Answer

EDIT : As per the question edit

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapRoute(
        name: "document",
        template: "Document/{id?}",
        defaults: new { controller = "Document", action = "Index" });
});

This route definition will work for all the route patterns you have

You do not need a specific route definition for the details url as it matches with the default convention(taken care by the default route definition). So it will work fine