2017-01-25 6 views
0

웹 API 2 프로젝트에 약간의 문제가 있습니다.웹 API 2 사용자 지정 성공/오류 개체를 반환하십시오.

내가 정의 성공/이런 식으로 오류 개체를 제공해야합니다 모바일 앱 클라이언트에 연결하려면 :

제품 (GET) 성공 (200)에

  • :와 목록을 반환 (ID, 이름) 오류에
  • : (ErrorCode가, ERRORDESCRIPTION)와 사용자 정의 개체를 반환

어떻게이 좋은 방법으로 할 수 있습니까? JsonResult을 사용하거나 더 좋은 방법이 있습니까?

답변

1

내가 이런 식으로 할 것 :

public class CustomErrorObject 
{ 
    public string ErrorCode { get; set; } 
    public string ErrorDescription { get; set; } 
} 

public class HandleApiExceptionAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) 
    { 
     base.OnException(actionExecutedContext); 

     HttpRequestMessage request = actionExecutedContext.ActionContext.Request; 
     CustomErrorObject response = new CustomErrorObject(); 
     response.ErrorCode = actionExecutedContext.Exception.Data("Text"); 
     response.ErrorDescription = actionExecutedContext.Exception.Data("Detail"); 

     actionExecutedContext.Response = request.CreateResponse(HttpStatusCode.BadRequest, response); 
    } 
} 

을 그 다음의 Global.asax에서 Application_Start 이벤트에이 줄을 추가 :

GlobalConfiguration.Configuration.Filters.Add(new HandleApiExceptionAttribute()) 

을 사용하면 예외 처리에 대한 자세한 내용을 알고 싶은 경우 웹 API : here