【问题标题】:DateTime as parameter to a WCF REST ServiceDateTime 作为 WCF REST 服务的参数
【发布时间】:2011-08-31 18:00:45
【问题描述】:

我有一个将 DateTime 作为参数的 Web 服务。如果用户传递的值格式不正确,.NET 会在它进入我的服务函数之前引发异常,因此我无法为客户端格式化一些好的 XML 错误响应。

例如:

[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。仅捕获表示日期格式无效的异常。

标签: c# wcf rest .net-4.0


【解决方案1】:

异常是预期的结果,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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多