Create nice url in asp.net core 3

Viewed 216

I want to have a URL that looks like:

if artCatId != null and tagId == null:

/Article/artCatId/100/pageNumber/2

or

if artCatId == null and tagId != null:

/Article/tagId/200/pageNumber/3

and if artCatId != null and tagId != null:

/Article/artCatId/100/tagId/200/pageNumber/3

How can I create this nice URL?

I've used ASP.NET Core 3.1 in my project.

in Controller:

public async Task<IActionResult> Index(int? artCatId = null, int? tagId = null, int pageNumber = 1)
{

}

in Startup.cs:

app.UseEndpoints(endpoints =>
{
    // This doesn't work based on my expectation
    endpoints.MapControllerRoute(name: "article cat or tag", pattern: "{controller=Article}/{action}/artCatId/{artCatId?}/tagId/{tagId?}/pageNumber/{pageNumber}");
}
2 Answers

One option is to place multiple RouteAtrributes on a single method:

[Route("Article/artCatID/{artCatId:int}/tagId/{tagId:int}/pageNumber/{pageNumber:int}")]
[Route("Article/artCatID/{artCatId:int}/pageNumber/{pageNumber:int}")] 
[Route("Article/tagId/{tagId:int}/pageNumber/{pageNumber:int}")] 
public IActionResult Article(int? artCatId = null, int? tagId = null, int pageNumber = 1)
{ 
   // logic to handle based on passed in values
} 

You can handle all this in the controller.

I have done this in a .net core application and tested all URL routes working to your specifications.

[Route("/Home/Article/ArtCatID/{artCatId:int}/TagId/{tagId:int}/PageNumber/{pageNumber:int}")]
        public IActionResult Article(int? artCatId = null, int? tagId = null, int pageNumber = 1)
        {
            //Do some Code here
            return View();
        }
        [Route("/Home/Article/ArtCatID/{artCatId:int}/PageNumber/{pageNumber:int}")]
        public IActionResult Article(int? artCatId = null, int pageNumber = 1)
        {
            //Do some Code here
            return View();
        }
        [Route("/Home/Article/TagId/{tagId:int}/PageNumber/{pageNumber:int}")]
        public IActionResult Article(int? tagId = null, int pageNumber = 1, string placeHolder = "")
        {
            //Do some Code here
            return View();
        }

This will handle the three scenarios you have above. No route mapping is needed in startup for this to work also. You will need three article methods, but that is actually nice in my opinion since you are going to have different results based on the URL

Related