1

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 ?

Serge
  • 40,935
  • 4
  • 18
  • 45
Sebastian
  • 4,625
  • 17
  • 76
  • 145
  • 1
    Your overview is accepted as pagesize. – Serge Feb 14 '21 at 16:17
  • I am thinking that ? is treating pagesize as optional and null also makes its optional. Should i do something more? – Sebastian Feb 14 '21 at 16:19
  • optional parameters in a route template should not have anything after them. Reconsider your desired route template – Nkosi Feb 14 '21 at 16:30
  • 2
    Like Sergey pointed, pagesize becomes overview when a value for pagesize is not supplied. I would be interested to see what the solution is, but you could just set your url like this `"overview/{identifier}/{itemsCount}/{pagesize?}"` Aside eliminating the issue, I think it makes more sense this way – Qudus Feb 14 '21 at 16:30
  • Can i make multiple routing rules to this action? One with pagesize and another one without pagesize? – Sebastian Feb 14 '21 at 16:32

1 Answers1

4

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)
{
            ....
}
Serge
  • 40,935
  • 4
  • 18
  • 45