2017-01-25 3 views
0

Web API 2プロジェクトで少し問題があります。私はこのようにカスタム成功/エラーオブジェクトを提供する必要がありますモバイルアプリのクライアントに接続するためにWeb 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()) 

を使用すると、例外処理についての詳細をお知りになりたい場合はin Web API:here

関連する問題