2011-08-31 125 views
3

我有一個Web服務,它將DateTime作爲參數。如果用戶傳遞一個格式不正確的值,.NET會在它進入我的服務函數之前拋出一個異常,因此我無法爲客戶端格式化一些很好的XML錯誤響應。DateTime作爲WCF REST服務的參數

例如:

[WebGet] 
public IEnumerable<Statistics> GetStats(DateTime startDate) 
{ 
    //.NET throws exception before I get here 
    Statistician stats = new Statistician(); 
    return ServiceHelper.WebServiceWrapper(startDate, stats.GetCompanyStatistics); 
} 

圍繞我的工作,現在(我強烈不喜歡)是:

[WebGet] 
public IEnumerable<Statistics> GetStats(string startDate) 
{ 
try 
{ 
    DateTime date = Convert.ToDateTime(startDat); 
} 
catch 
{ 
    throw new WebFaultException<Result>(new Result() { Title = "Error", 
    Description = "startDate is not of a valid Date format" }, 
    System.Net.HttpStatusCode.BadRequest); 
} 
Statistician stats = new Statistician(); 
return ServiceHelper.WebServiceWrapper(startDate, stats.GetCompanyStatistics); 
} 

有我丟失的東西嗎?看起來應該有一個更乾淨的方式來做到這一點。

+2

我不會用空'catch'。僅捕獲意味着日期格式無效的例外。 –

回答

3

異常是預期的結果,re:傳遞的參數不是DateTime類型。如果一個數組作爲參數傳遞給一個int,那麼這將是相同的結果。

您爲該方法創建另一個簽名的解決方案當然是可行的。該方法接受一個字符串作爲參數,嘗試將該值解析爲日期,如果成功,則調用期望DateTime作爲參數的方法。

[WebGet] 
public IEnumerable<Statistics> GetStats(DateTime startDate) 
{ 
    var stats = new Statistician(); 
    return ServiceHelper.WebServiceWrapper(startDate, stats.GetCompanyStatistics); 
} 

[WebGet] 
public IEnumerable<Statistics> GetStats(string startDate) 
{ 
    DateTime dt; 
    if (DateTime.TryParse(startDate, out dt)) 
    { 
    return GetStats(dt); 
    } 

    throw new WebFaultException<Result>(new Result() { Title = "Error", 
    Description = "startDate is not of a valid Date format" }, 
    System.Net.HttpStatusCode.BadRequest); 
}