Skip to main content
 首页 » 编程设计

c#之Web API 2 返回错误并让 http.post 捕获它

2024年01月31日27jirigala

到目前为止,如果发生 web api 2 错误并且我捕获了它,我会返回一个自定义对象并填写捕获的错误消息。然而,这会使实际的 http.post() 进入成功方法而不是错误,然后我必须查看我自己的 bool 成功变量,如果为真则一切正常,如果为假则显示错误。这有点烦人,因为出于 2 个不同的原因,我必须在 2 个不同的地方查找错误。在 Web API 2 中,如果我在 Web API Controller 中发现错误,是否有一种方法可以让 http.post() 在我填写错误消息时触发错误回调?

[HttpPost] 
public MyResponseObject UpdateData(RequestObject req) 
{ 
   MyResponseObject resp = new MyResponseObject(); 
   resp.Success = true; 
 
   try{ 
      // error happens here 
   }catch(Exception ex){ 
      resp.Success = false; 
      resp.Msg = ex.Message; 
   } 
 
   return resp; 
} 

http.post() 调用仍然会成功,但现在我必须查看 resp.Success 的成功回调,看看它是否真的成功了。当然可以进行 API 调用,但其中出现了问题。我只想显示该消息并使调用失败,以便使用异常消息调用 http.post() 错误回调。

请您参考如下方法:

只是抛出一个异常:

throw new HttpResponseException(HttpStatusCode.InternalServerError); 

如果您想自定义返回的响应,您可以创建一个包含更多详细信息的 HttpResponseMessage:

var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) 
{ 
    Content = new StringContent("We messed up"), 
    ReasonPhrase = "Error" 
} 
throw new HttpResponseException(resp); 

文档 here