【问题标题】:Optional date parameter using Route attribute in web API在 Web API 中使用 Route 属性的可选日期参数
【发布时间】:2019-07-23 08:20:11
【问题描述】:

我希望我的 API 方法有两个端点:

api/bids/

api/bids/{yyyy-MM-dd}

在第一种情况下,我会将未定义的日期映射为今天

我尝试过这样做,但没有成功:

    [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);
            }

        }
    }

在我的情况下,如何将可选的日期参数与属性路由一起使用?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-routing


    【解决方案1】:

    你需要让你的参数在路由和默认的空分配中是可选的:

    您的端点路由也需要更改为不包含 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);
            }
    
        }
    }
    

    为了阅读方便,我把这一行改了

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

    到这里

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

    【讨论】:

    • 此方法对/api/bids//api/bids/2019-01-01 请求均返回404 错误。
    • 这可能是完全错误的,因为有一段时间没有使用 Route 前缀了。但是您的设置不会导致路由为 api/bids/api/bids/2019-01-01 - 让我知道这是否能解决问题,我会更改我的答案以使用正确的路由
    • 您可以尝试将端点路由更改为此:[HttpGet, Route("{dateTime:DateTime?}")] 让我知道这是否解决了您的问题,如果没有,那么我已经退出了想法...
    • 它工作得很好thanx!我了解该问题与重复的 RoutePrefix 相关
    • 没问题,只是更改了我原来的答案以反映这一点
    猜你喜欢
    • 2017-08-11
    • 2014-05-11
    • 1970-01-01
    • 2017-06-26
    • 2014-04-18
    • 2017-07-14
    • 2014-02-19
    • 2016-11-09
    • 2018-06-13
    相关资源
    最近更新 更多