我有一个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';
}
}
答案 0 :(得分:4)
如果您在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错误。
答案 1 :(得分:3)
不要回来,而是扔掉。
throw new HttpResponseException(HttpStatusCode.Unauthorized);
答案 2 :(得分:1)
好吧,因为&#34;字符串&#34;您的第二条消息是由异常引起的,应按照以下方式处理:
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;
}
正如您可以看到上面的示例,您可以将特定级别的信息作为异常的一部分传递给客户端进行正确处理。
答案 3 :(得分:1)
您可以创建一些类似
的通用api响应模型ROUND
而不是你的回复
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
}
答案 4 :(得分: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
}
您可以回复的响应消息,例如&#34;您的数据已成功保存。&#34;
以下是如何使用此
的好例子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;
}
}
所有apis都应该遵循这一点。我们在webapi中使用这种通用解决方案。到现在为止它非常好。