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);
}
有我丟失的東西嗎?看起來應該有一個更乾淨的方式來做到這一點。
我不會用空'catch'。僅捕獲意味着日期格式無效的例外。 –