Search code examples
c#asp.net-coreurlurl-routingasp.net-core-3.0

Create nice url in asp.net core 3


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}");
}

Solution

  • 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
    }