如何通过日期时间的参数? [英] How to pass a datetime parameter?

查看:124
本文介绍了如何通过日期时间的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过UTC日期与Web API?

传递 2010-01-01 工作正常,但是当我通过UTC日期,例如 2014-12-31T22:00:00.000Z (带有时间组件),我得到一个HTTP 404响应。因此,

 的http://域名/ API /控制器/动作/ 2012-12-31T22:00:00.000Z

产生一个404错误响应,而

 的http://域名/ API /控制器/动作/ 2012-12-31

正常工作。

如何通过UTC日期对Web API,然后 - 或者至少指定日期的的时间


解决方案

我觉得你的痛苦......另一个日期和时间格式......你需要的正是!

使用网页API 2,您可以使用路由属性来指定参数。

所以对你的类属性,以及你的方法,你可以使用你遇到的麻烦这UTC格式code了REST URL(显然它ISO8601,presumably到达使用startDate.toISOString())

<$p$p><$c$c>[Route(@\"daterange/{startDate:regex(^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z$)}/{endDate:regex(^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z$)}\")]
    [HTTPGET]
    公共IEnumerable的&LT; MyRecordType&GT; GetByDateRange(日期时间的startDate,日期结束日期)

......但是,虽然这可以与一个日期(的startDate),由于某种原因,它不工作时,结束日期为这种格式...调试了好几个小时,唯一的线索是例外,说:它不象冒号: (即使web.config中设置有:

 &LT;&的System.Web GT;
    &LT;编译调试=真targetFramework =4.5.1/&GT;
    &LT;的httpRuntime targetFramework =4.5.1requestPathInvalidCharacters =/&GT;
&LT; /system.web>

因此​​,让使另一个日期格式(从填充工具为ISO日期格式拍摄),并把它添加到的Javascript日期(为简便起见,只转换到分钟):

 如果(!Date.prototype.toUTCDateTimeDigits){
    (函数(){        功能垫(数){
            如果(数小于10){
                返回'0'+号;
            }
            返回数;
        }        Date.prototype.toUTCDateTimeDigits =功能(){
            返回this.getUTCFullYear()+
              垫(this.getUTCMonth()+ 1)+
              垫(this.getUTCDate())+
              'T'+
              垫(this.getUTCHours())+
              垫(this.getUTCMinutes())+
              Z;
        };    }());
}

然后,当你发送的日期到Web API 2的方法,你可以从他们的字符串转换为日期:

  [路线preFIX(API / myrecordtype)]
公共类MyRecordTypeController:ApiController
{
    [路线(@日期范围/ {startDateString} / {} endDateString)]
    [HTTPGET]
    公共IEnumerable的&LT; MyRecordType&GT; GetByDateRange([FromUri]串startDateString,[FromUri]字符串endDateString)
    {
        VAR的startDate = BuildDateTimeFromYAFormat(startDateString);
        VAR结束日期= BuildDateTimeFromYAFormat(endDateString);
    ...
    }    ///&LT;总结&gt;
    ///转换格式yyyyMMddThhmmZ的UTC日期字符串成当地的日期
    ///&LT; /总结&gt;
    ///&LT; PARAM NAME =dateString&GT;&LT; /参数&GT;
    ///&LT;&回报GT;&LT; /回报&GT;
    私人的DateTime BuildDateTimeFromYAFormat(字符串dateString)
    {
        正则表达式R =新的正则表达式(@^ \\ D {4} \\ d {2} \\ d {2}牛逼\\ D {2} \\ d {2} Z $);
        如果(!r.IsMatch(dateString))
        {
            抛出新FormatException(
                的String.Format({0}不是正确的格式应该是yyyyMMddThhmmZ,dateString));
        }        DateTime的DT = DateTime.ParseExact(dateString,yyyyMMddThhmmZ,CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal);        返回DT;
    }

这样的网址是

 的http://域名/ API / myrecordtype /日期范围/ 20140302T0003Z / 20140302T1603Z

Hanselman的在这里给出了一些相关的信息:

<一个href=\"http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx\">http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

How to pass UTC dates to Web API?

Passing 2010-01-01 works fine, but when I pass a UTC date such as 2014-12-31T22:00:00.000Z (with a time component), I get a HTTP 404 response. So

http://domain/api/controller/action/2012-12-31T22:00:00.000Z

yields a 404 error response, while

http://domain/api/controller/action/2012-12-31

works fine.

How to pass UTC dates to Web API then - or at least specify date and time?

解决方案

I feel your pain ... yet another date time format... just what you needed!

Using Web Api 2 you can use route attributes to specify parameters.

so with attributes on your class and your method you can code up a REST URL using this utc format you are having trouble with (apparently its ISO8601, presumably arrived at using startDate.toISOString())

[Route(@"daterange/{startDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}/{endDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange(DateTime startDate, DateTime endDate)

.... BUT, although this works with one date (startDate), for some reason it doesnt work when the endDate is in this format ... debugged for hours, only clue is exception says it doesnt like colon ":" (even though web.config is set with :

<system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" requestPathInvalidCharacters="" />
</system.web>

So, lets make another date format (taken from the polyfill for the ISO date format) and add it to the Javascript date (for brevity, only convert up to minutes):

if (!Date.prototype.toUTCDateTimeDigits) {
    (function () {

        function pad(number) {
            if (number < 10) {
                return '0' + number;
            }
            return number;
        }

        Date.prototype.toUTCDateTimeDigits = function () {
            return this.getUTCFullYear() +
              pad(this.getUTCMonth() + 1) +
              pad(this.getUTCDate()) +
              'T' +
              pad(this.getUTCHours()) +
              pad(this.getUTCMinutes()) +
              'Z';
        };

    }());
}

Then when you send the dates to the Web API 2 method, you can convert them from string to date:

[RoutePrefix("api/myrecordtype")]
public class MyRecordTypeController : ApiController
{


    [Route(@"daterange/{startDateString}/{endDateString}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange([FromUri]string startDateString, [FromUri]string endDateString)
    {
        var startDate = BuildDateTimeFromYAFormat(startDateString);
        var endDate = BuildDateTimeFromYAFormat(endDateString);
    ...
    }

    /// <summary>
    /// Convert a UTC Date String of format yyyyMMddThhmmZ into a Local Date
    /// </summary>
    /// <param name="dateString"></param>
    /// <returns></returns>
    private DateTime BuildDateTimeFromYAFormat(string dateString)
    {
        Regex r = new Regex(@"^\d{4}\d{2}\d{2}T\d{2}\d{2}Z$");
        if (!r.IsMatch(dateString))
        {
            throw new FormatException(
                string.Format("{0} is not the correct format. Should be yyyyMMddThhmmZ", dateString)); 
        }

        DateTime dt = DateTime.ParseExact(dateString, "yyyyMMddThhmmZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

        return dt;
    }

so the url would be

http://domain/api/myrecordtype/daterange/20140302T0003Z/20140302T1603Z

Hanselman gives some related info here:

http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

这篇关于如何通过日期时间的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆