【问题标题】:WCF REST ParametersWCF REST 参数
【发布时间】:2014-01-31 08:12:04
【问题描述】:

我正在 wcf 休息服务中编写一个方法。方法是get方法,参数是日期。我如何在 jquery 中使用参数作为服务消耗。

如果我使用 templateUri,它必须是字符串。示例:

[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetProductionDay/{shiftDate}")]

否则我可以使用 DateTime 之类的查询字符串。示例:

[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetProductionDay?shiftDate={shiftDate}")]

哪个合适?像这样,我有多个带有 int、datetime 等的参数。所以如果我使用第一个参数,所有的东西都必须是字符串。我对吗? 如果我关注第二个任何类型的任何问题?

【问题讨论】:

标签: c# jquery wcf rest


【解决方案1】:

在这种情况下,我通常使用 UTC 日期表示(从 01.01.1970 开始的秒数/毫秒)。在 JavaScript 方面,它可以是

var utc = new Date().getTime() / 1000;

在服务器端可以通过以下逻辑进行管理:

public static class DateTimeExtensions
{
    static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    static readonly double _maxUnixSeconds = (DateTime.MaxValue - _unixEpoch).TotalSeconds;

    /// <summary>
    /// Converts .NET <c>DateTime</c> to Unix timestamp used in JavaScript
    /// </summary>
    /// <param name="dateTime">DateTime to convert</param>
    /// <returns>Unix timestamp in seconds</returns>
    public static long ToUnixTimestamp(this DateTime dateTime)
    {
        return (long)(dateTime - _unixEpoch).TotalSeconds;
    }


    public static DateTime FromUnixTimestamp(long seconds)
    {
        return _unixEpoch.AddSeconds(seconds);
    }

    public static DateTime? FromUnixTimestamp(string seconds)
    {
        long secondsNo;
        if(String.IsNullOrEmpty(seconds) || !long.TryParse(seconds, out secondsNo))
        {
           retun null;
        }

        return _unixEpoch.AddSeconds(secondsNo);
    }
}

使用此 loigc,您可以在客户端将所有日期转换为简单数字,并在服务器端使用 DateTime? 以正确处理空日期

[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetProductionDay/{shiftDate}")]
public int GetProductionDay (string shiftDate) 
{
    DateTime? dt = DateTimeExtensions.FromUnixTimestamp(shiftDate);  
    ....
    return res;
}

更多信息:How to convert a Unix timestamp to DateTime and vice versa?

【讨论】:

  • 很好,但如果我需要在没有时间的情况下传递特定数据如何使用它。例如:'25/12/2013'
  • 我可以使用这个并且工作。但我的困惑在于日期对象。 new Date() 代表 UTC ,然后我如何像上面的评论一样给出一个具体的发送日期
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多