[英]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.