[英]Returning a HTTP status code based on an XML response with no status code
我正在實現一個 RESTful API,該 API 調用第三方服務,該服務在失敗時返回這樣的 XML 響應:
<Status>Failure</Status>
<ErrorContent>One or more do not exist</ErrorContent>
<ErrorNum>20</ErrorNum>
當第三方返回失敗時,我想向我的 API 的用戶返回400
響應。 最好的方法是什么? 我總是可以檢查Status
是Success
還是Failure
並相應地返回,但似乎應該有更好的方法來做到這一點。
我不認為有更好的方法來做到這一點。 XML 是您正在使用的服務的專有,所以我不知道任何“內置”來處理它。 您可以創建一個負責處理此問題的新類,或者實現一個基礎抽象類,該類可以由使用這種類型 XML 的所有 API 控制器繼承。
public abstract class myApiController : ControllerBase
{
protected IActionResult Response(string xmlresponse, object responseObject)//your "responseobject", you could remove this and return OKResult instead of OKObjectResult
{
if (IsSuccessXML(xmlresponse))
return new OkObjectResult(responseObject);
return new BadRequestResult();
}
private bool IsSuccessXML(string yourxmlResponse)//you could use the xml object instead of string
{
//read your xml response and "treat the response accordingly", returning true or false; you could also use the response object to show the errors to the users consuming your api
return false;
我同意其他答案。 我會封裝對 3rd 方服務的調用並返回成功或失敗。 然后根據您在每種情況下想要做什么,返回 400 或 200 或您需要的任何內容。 我認為沒有任何魔法可以使流程變得更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.