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