开发者

DateTime as parameter to a WCF REST Service

I have a web service which takes a DateTime as a parameter. If a user passes a value that is not of the correct format, .NET throws an exception before it ever goes into my Service function and therefore I cannot format some nice XML error response for the client.

For example:开发者_如何学运维

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

My work around right now (which I strongly dislike) is:

[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);
}

Is there something I am missing here? It seems there should be a cleaner way of doing this.


The exception is the expected result, re: the parameter passed is not of type DateTime. This would be the same result if an array were passed as a parameter that was expecting an int.

Your solution of creating another signature for the method is certainly viable. The method accepts a string as a parameter, attempts to parse the value as a date, if it succeeds, then call the method that is expecting the DateTime as a parameter.

Example

[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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜