我有一个非常简单的 Web API,只有 GET Controller 。在 get Controller 中,我正在读取一个 XML 文件,将该 XML 文件转换为一个 JSON 对象并返回它。
public JObject Get()
{
//Read XML
XDocument xDoc = XDocument.Load(@"D:\myfile.xml");
string jsonStr = JsonConvert.SerializeXNode(xDoc);
JObject json = JObject.Parse(jsonStr);
return json;
}
我想将 XML 读取和 JSON 转换行放入异常处理程序中,如果无法打开 XML 文件(或任何其他发生异常)。但是由于我的返回类型 id JObject
,我无法返回正确的 http 响应,那么我该怎么做呢?
最佳答案
您应该将 Action Method 的返回类型更改为 IHttpActionResult
然后您可以执行类似这样的操作
public IHttpActionResult Get()
{
if (!File.Exists(@"D:\myfile.xml"))
return NotFound();
//Read XML
XDocument xDoc = XDocument.Load(@"D:\myfile.xml");
string jsonStr = JsonConvert.SerializeXNode(xDoc);
JObject json = JObject.Parse(jsonStr);
return Ok(json);
}
这应该会为您提供所需的灵 active 。
所用方法的快速说明
return OK(json)
将返回一个成功的 (HTTP 200) 响应,主体中包含序列化的 json
。
return NotFound()
将导致请求失败和 HTTP 404 结果。
对于错误,理想情况下您应该返回一个 5xx 代码,这可以通过 return InternalServerError();
有关 ApiController
基类中的这些和其他助手的更多信息,请查看 page on microsoft docs
关于c# - 如何返回正确的 Http 响应而不是 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703986/