简体   繁体   English

在 Web API 中使用 Route 属性的可选日期参数

[英]Optional date parameter using Route attribute in web API

I want to have two endpoints to my API method:我希望我的 API 方法有两个端点:

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?在我的情况下,如何将可选日期参数与属性路由一起使用?

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此外,您的端点路由需要更改为不包含 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?}")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM