Search code examples
c#asp.net-web-apiasp.net-web-api-routing

How to create a route attribute which handles missing middle parameters?


If I have the code below and when the firstname is missing in the url, I get a 404 error. See first example below. I am not sure why the route doesn't work in this case when the attribute names are in the url are there are placeholders for the values. My solution is to create another route and use another url format but that's more work. What if I have many parameters and some in the middle are missing their values, isn't there a single route that can handle all of the instances? How do I create a single route which can handle the four combinations in the below example? Both are missing. Both are present. One of them is missing.

[HttpGet]
[Route("getcustomer/firstname/{firstname?}/status/{status?}")]      
public IHttpActionResult GetCustomer(string firstname = null, string status = null)
{
    ... some code ...
}

**Example URLs:**  
http://.../getcustomer/firstname//status/valid"       causes 404
http://.../getcustomer/firstname/john/status/active"   good
http://.../getcustomer/firstname/john/status/"        good

Solution

  • That is by design. You may need to create another action to allow for that. Also in terms of how the framework is built. the end segments are the ones that should be optional.

    You need to rethink your design.

    For example

    [RoutePrefix("api/customers")]
    public class CustomersController : ApiController {
    
        [HttpGet]
        [Route("")] // Matches GET  api/customers
        public IHttpActionResult GetCustomer(string firstname = null, string status = null) {
            ... some code ...
        }
    }
    

    Example URLs:
    http://...api/customers
    http://...api/customers?status=valid
    http://...api/customers?firstname=john&status=active
    http://...api/customers?firstname=john