Search code examples
c#.netasp.net-mvc.net-coreasp.net-mvc-routing

.Net core MVC Controller with optional parameter routing rules breaking with null values


Wirking on a .net core app and the Startup settings are like below

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

There is a custom controller and definition of the controller is like below

[Route("Purchase")]
public class InvoiceController : Controller
{
    [HttpGet("{identifier}/{itemsCount}/overview")]
    public async Task<IActionResult> GetInvoiceOverview(string identifier,int itemsCount)
    { 
        A call to url like this //https://localhost:44320/invoice/20210209-0035/20/overview/  

        is working correctly and getting param values as 

        identifier=20210209-0035
        itemsCount=20
        
    }   
}

I am trying to add one more optional param to this list and the new action definition is like this now

    [HttpGet("{identifier}/{itemsCount}/{pagesize?}/overview")]
    public async Task<IActionResult> GetInvoiceOverview(string identifier,int itemsCount,string pagesize=null)
    { 
        
    }
         

This ruting rules seems to be working for all non null values of pagesize , like below https://localhost:44320/invoice/20210209-0035/20/11/overview/ is also working and getting params as below

        identifier=20210209-0035
        itemsCount=20
        pagesize=11     

But when try to make a call with null value of pagesize the application is returning 404 Page Not found
This url : https://localhost:44320/invoice/20210209-0035/20/overview/ => 404

What might be the reason behind this ?


Solution

  • You can try to use 2 attribute routes

    [HttpGet("~/invoice/{identifier}/{itemsCount}/overview")]
    [HttpGet("~/invoice/{identifier}/{itemsCount}/{pagesize:int}/overview")] //:int is optional
    public async Task<IActionResult> GetInvoiceOverview(string identifier, int itemsCount, int?  pagesize)
    {
                ....
    }