[英]Return different types from a single method c# web api
我有一個Web API,調用時會返回一個客戶對象。 但是,如果發生錯誤,我想返回一個錯誤字符串。 但是,如何在單個C#方法中返回不同的類型。
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';
}
}
如果您發布的代碼位於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");
}
}
如果您的代碼在服務中,則可以在控制器中執行相同的操作,但是會從服務中引發自定義異常,如下所示:
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個錯誤。
不返回,而是拋出。
throw new HttpResponseException(HttpStatusCode.Unauthorized);
好吧,由於您的第二條消息是“字符串”,是由於異常所致,因此應按以下方式處理:
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;
}
如您所見,上面的示例可以將某些級別的信息作為異常的一部分傳遞給客戶端,以進行正確的處理。
您可以創建一些通用的api響應模型,例如
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
}
比你的回應
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;
}
我更喜歡通用解決方案。
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 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;
}
這是句柄響應類
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中都應遵循此規則。 我們正在webapi中使用此通用解決方案。 到現在為止,一切都很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.