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'。仅捕获意味着日期格式无效的例外。 –