2011-08-31 5 views
3

DateTime을 매개 변수로 사용하는 웹 서비스가 있습니다. 사용자가 올바른 형식이 아닌 값을 전달하면 .NET은 예외가 발생하기 전에 서비스 기능에 들어가기 때문에 클라이언트에 대해 좋은 XML 오류 응답을 형식화 할 수 없습니다. 예를 들어WCF REST 서비스의 매개 변수로 DateTime

:

지금 (난 강력하게 싫어한다)의 주위에
[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

전달 된 매개 변수의 형식이 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); 
} 
관련 문제