2014-01-31 55 views
0

我正在寫一個wcf rest服務的方法。方法是get方法,參數是date。我如何使用參數作爲服務在jQuery中消費。WCF REST參數

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

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

否則,我可以使用DateTime查詢字符串。例如:

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

哪一個適合?像這樣我有多個參數與int,日期時間等。所以,如果我去與第一個所有的東西必須是字符串。我對嗎? 如果我關注第二個任何類型的問題?

+0

只是一個觀察 - 你可能會發現它更容易使用新的Web API,而不是純醇」 WCF - 看到這個SO問題... http://stackoverflow.com/questions/9348639/wcf-vs-asp-net-web-api – Jay

+0

好thougfht其實我也在想它。但我對mvc模型很陌生,也沒有人幫我在我的辦公室 – Akhil

回答

0

在這種情況下,我通常使用UTC日期表示法(從1970年1月1日起計秒/ ms)。在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你可以轉換在客戶端的所有日期以簡單的數字和使用日期時間?在服務器端正確空日期工作

[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?

+0

好,但如果我需要傳遞一個特定的數據沒有時間如何使用這個。例如:'25/12/2013' – Akhil

+0

我可以使用這個工作。但我的困惑在於日期對象。新的日期()代表UTC,那麼我如何給出具體的日期發送像我上面的評論 – Akhil