2017-09-22 14 views
0

呼び出されたときに顧客オブジェクトを返すWeb APIがあります。しかし、エラーが発生した場合、私はエラー文字列を返したい。しかし、C#の単一のメソッドで異なる型を返す方法。単一のメソッドから異なる型を返すC#web api

public IEnumerable<Customers> getCustomersById(string id){ 

     var isAuthenticated = tokenAuthorization.validateToken(access_token); 
     if (isAuthenticated) 
     { 
      List<Customers> customers = new List<Customers>(); 
      Customers customer = null; 
      customer = new Customers(); 
      customer.kunnr = id; 
      customer.name = "John Doe"; 
      customers.Add(customer); 
      return customers; 
     } 
     else 
     { 
      return 'Not a valid Access Token'; 
     } 

} 

答えて

3

public class ApiResponse<T>{ 
public T Data {get;set;} // it will contains the response 
public string Message {get;set;} // here you can put you error message 
public boolean IsSuccess {get;set;} //this will be true only when no error 
} 

のようないくつかの一般的なAPIレスポンスモデルのものを作成し、あなたの応答に比べできます

public IHttpActionResult getCustomersById(string id){ 

    var isAuthenticated = tokenAuthorization.validateToken(access_token); 
    if (isAuthenticated) 
    { 
     List<Customers> customers = new List<Customers>(); 
     Customers customer = null; 
     customer = new Customers(); 
     customer.kunnr = id; 
     customer.name = "John Doe"; 
     customers.Add(customer); 
     return Ok(customers); 
    } 
    else 
    { 
     return BadRequest("Not a valid Access Token"); 
    } 
} 

コードがサービスに含まれている場合は、同じことをコントロールで実行できますRしかし、あなたのサービスからカスタム例外をスローし、このような何か:

public IEnumerable<Customers> getCustomersById(string id){ 

    var isAuthenticated = tokenAuthorization.validateToken(access_token); 
    if (isAuthenticated) 
    { 
     List<Customers> customers = new List<Customers>(); 
     Customers customer = null; 
     customer = new Customers(); 
     customer.kunnr = id; 
     customer.name = "John Doe"; 
     customers.Add(customer); 
     return customers; 
    } 
    else 
    { 
     throw new TokenInvalidException("Not a valid Access Token"); 
    } 
} 

そしてコントローラにあなたはそのAPI呼び出しの内部でそのエラーをキャッチし、私が以前に示されたのと同じ戻り値の型とメソッドを使用することができます例。または、汎用エラーハンドラもそのエラーを処理できます。カスタムエラーを使用している場合は、独自のエラーハンドラフィルタを実装することをおすすめしますが、500エラーは返されません。

3

返さず、代わりにスローします。

「文字列」はそれのようなとして扱うべきである 例外が原因で、あなたの2番目のメッセージ以来まあ
throw new HttpResponseException(HttpStatusCode.Unauthorized); 
1

:あなたが渡すことができ、上記あなたが例を見ることができるように

public IEnumerable<Customers> getCustomersById(string id){ 

     var isAuthenticated = tokenAuthorization.validateToken(access_token); 
     if (isAuthenticated) 
     { 
      List<Customers> customers = new List<Customers>(); 
      Customers customer = null; 
      customer = new Customers(); 
      customer.kunnr = id; 
      customer.name = "John Doe"; 
      customers.Add(customer); 
      return customers; 
     }else 
     { 
     var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
     { 
      Content = new StringContent(string.Format("No person with ID = {0}", id)), 
      ReasonPhrase = "Person ID Not Found" 
     } 
     throw new HttpResponseException(resp); 
    } 
    return item; 
} 

クライアント側で適切な処理を行うための例外の一部として、特定のレベルの情報に基づいています。

1

コードはあなたがこれを行うことができますよりも、それがAPIコントローラにあります投稿した場合あなたは

public ApiResponse<IEnumerable<Customers>> getCustomersById(string id){ 
var retVal = new ApiResponse<IEnumerable<Customers>>(); 
var isAuthenticated = tokenAuthorization.validateToken(access_token); 
if(!isAuthenticated){ 
retVal.Message="You are not authrized"; 
return retVal; 
} 
try{ 
var data = yourList; 
retVal.IsSuccess = true; 
retVal.Data = yourList; 
} 
catch(exception ex){ 
retVal.Message=yourmessage; 
} 
return retVal; 
} 
1

これは一般的な解決策を希望します。ここで

public class ResponseList<T> { 

     public ResponseList() { 
      Exceptions = new Dictionary<string, string>(); 
     } 

     public ResposeCodes ResposeCode { get; set; } = ResposeCodes.Success; 

     public Dictionary<string, string> Exceptions { get; set; } = null; 

     public List<T> DataList { get; set; } = null; 

     public string ResponseMessage { get; set; } = null; 
    } 

レスポンスコードは次のようになりする必要があります:「あなたのデータが正常に保存された」あなたのような応答を与えることができ

public enum ResposeCodes 
    { 
     Error = 1, 
     Success = 2, 
     NoDataFound = 3 
    } 

応答メッセージ

はここでここでハンドルレスポンスクラス

public static class HandleResponse { 
     public static void AddException<T>(Exception ex, ref ResponseList<T> response) { 
      response.ResposeCode = ResposeCodes.Error; 
      response.Exceptions.Add(ResposeCodes.Error.ToString(), ex.Message); 


      //inserting errors into table     

     } 

     public static void AddErrorMessage<T>(string message, ref ResponseList<T> r) { 
      r.ResposeCode = ResposeCodes.Error; 
      r.ResponseMessage = message; 
     } 

     public static void AddSuccessMessage<T>(string message, ref ResponseList<T> r) { 
      r.ResposeCode = ResposeCodes.Success; 
      r.ResponseMessage = message; 
     } 
    } 

これは、すべてのAPIに従うべきである。この

public ResponseList<Model> GetData(string ta_id) { 
      ResponseList<Model> response = new ResponseList<Model>(); 
      List<Model> res = null; 
      try 
      { 
       res = new List<Model>(); 
       //perform your operations 
       res.data = responselist; 
      } 
      catch (Exception ex) 
      { 
       HandleResponse.AddException(ex, ref response); 
      } 
      response.DataList = res; 
      return response; 
     } 

を使用する方法の良い例です。私たちはwebapiでこの汎用ソリューションを使用しています。今まではとても良い状態になっています。

関連する問題