1

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?

1 Answer 1

1

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?}")]
Sign up to request clarification or add additional context in comments.

5 Comments

This approach returns a 404 error for both /api/bids/ and /api/bids/2019-01-01 requests.
This might be completely wrong, as haven't used Route prefix in a while. But doesn't your setup cause the route to be api/bids/api/bids/2019-01-01 - Let me know if that fixes the issue and I will change my answer to use correct routing also
Can you just try changing the Endpoint route to this: [HttpGet, Route("{dateTime:DateTime?}")] Let me know if that fixes your issue, if not then I am out of ideas...
It works fine thanx! I understand that problem was related with duplicated RoutePrefix
No problem, just changed my original answer to reflect this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.