2011-08-31 127 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); 
}