Creating a route that can accept a DateTime in the URI with asp.net web api 2 attribute routing

时光怂恿深爱的人放手 提交于 2019-12-06 03:12:21

Web API datetime constraint doesn't do anything special regarding parsing datetime as you can notice below(source code here). If your request url is like var/1/slot/2012-01-01 1:45:30 PM or var/1/slot/2012/01/01 1:45:30 PM, it seems to work fine...but I guess if you need full flexibility then creating a custom constraint is the best option...

public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
    if (parameterName == null)
    {
        throw Error.ArgumentNull("parameterName");
    }

    if (values == null)
    {
        throw Error.ArgumentNull("values");
    }

    object value;
    if (values.TryGetValue(parameterName, out value) && value != null)
    {
        if (value is DateTime)
        {
            return true;
        }

        DateTime result;
        string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
        return DateTime.TryParse(valueString, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
    }
    return false;
}

an option is to pass the DateTime as query string parameters (see [FromUri]

e.g.

[Route("api/Customer/{customerId}/Calls/")]
public List<CallDto> GetCalls(int customerId, [FromUri]DateTime start, [FromUri]DateTime end)

this will have a signature of

GET api/Customer/{customerId}/Calls?start={start}&end={end}

Create the query string dates with

startDate.ToString("s", CultureInfo.InvariantCulture);

query string will look like

api/Customer/81/Calls?start=2014-07-25T00:00:00&end=2014-07-26T00:00:00
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!