2012-06-27 4 views
6

다음 코드를 사용하여 필터 (ActionFilterAttribute)에서 클라이언트로 오류 메시지를 보냅니다.catch 블록에서 클라이언트에 형식화 된 오류 메시지 보내기

catch (Exception) 
{ 
    var response = context.Request.CreateResponse(httpStatusCode.Unauthorized); 
    response.Content = new StringContent("User with api key is not valid"); 
    context.Response = response; 
} 

그러나 문제는 일반 텍스트로만 보내는 것입니다. 나는 그것을 현재 포매터의 형식으로 보내고 싶다. json 또는 xml 형식과 비슷합니다.

여기 내가 StringContent()를 사용하고 있기 때문에이 사실을 알고 있습니다. 하지만 어떻게 사용자 정의 Error 객체를 사용하여 작성할 수 있습니까? 같은, 다음 작동하지 않는 경우 다음 중 하나를

response.Content = new Error({Message = "User with api key is not valid"}); 

어떻게 우리가 이것에 대한 코드를 작성합니까? 미리 감사드립니다.

답변

8

예, 올바른 구문 쓰기를 발견했습니다. 우리는 다음과 같이 쓸 수 있습니다 :

catch (Exception) 
{ 
    var response = context.Request.CreateResponse(HttpStatusCode.NotFound, 
         new Error { Message = "User with api key is not valid"}); 
    context.Response = response; 
} 
+0

어떻게 이것을 MVC 3에서 할 수 있습니까? –

관련 문제