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

Optional date parameter using Route attribute in web API


I want to have two endpoints to my API method:

api/bids/

and

api/bids/{yyyy-MM-dd}

In first case i will map undefined date as today

I tried to make this way, but it did not work:

    [RoutePrefix("api/bids")]
    public class BidsController : ApiController
    {

        [HttpGet, Route("api/bids/{dateTime?}")]
        public async Task<IHttpActionResult> GetBids(DateTime? dateTime = null)
        {

            var correctDate = (dateTime != null) && (dateTime.Value >= DateTime.Now.Date);
            DateTime date = correctDate ? dateTime.Value : DateTime.Now.Date;

            try
            {
                return Ok(date);
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                return BadRequest(errorMessage);
            }

        }
    }

How i can use optional date parameter with attribute routing in my case?


Solution

  • You need to make your parameter optional within the route as well as the default null assigning:

    Also your Endpoint route needs to be changed to not include api/bids

    [RoutePrefix("api/bids")]
    public class BidsController : ApiController
    {
        [HttpGet, Route("{dateTime:DateTime?}")]
        public async Task<IHttpActionResult> GetBids(DateTime? dateTime = null)
        {
    
            var correctDate = (dateTime != null) && (dateTime.Value >= DateTime.Now.Date);
            DateTime date = correctDate ? dateTime.Value : DateTime.Now.Date;
    
            try
            {
                return Ok(date);
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                return BadRequest(errorMessage);
            }
    
        }
    }
    

    For ease of reading, I have changed this line

    [HttpGet, Route("api/bids/{dateTime?}")]
    

    to this

    [HttpGet, Route("{dateTime:DateTime?}")]