我有一个 API Controller 端点,例如:
public IHttpActionResult AddItem([FromUri] string name)
{
try
{
// call method
return this.Ok();
}
catch (MyException1 e)
{
return this.NotFound();
}
catch (MyException2 e)
{
return this.Content(HttpStatusCode.Conflict, e.Message);
}
}
这将在正文中返回一个字符串,如 “这是你的错误信息”
,有什么方法可以返回带有“Content”的 JSON 吗?
例如,
{
"message": "here is your error msg"
}
最佳答案
只需将所需的对象模型构建为匿名对象并返回即可。
目前您只返回原始异常消息。
public IHttpActionResult AddItem([FromUri] string name) {
try {
// call service method
return this.Ok();
} catch (MyException1) {
return this.NotFound();
} catch (MyException2 e) {
var error = new { message = e.Message }; //<-- anonymous object
return this.Content(HttpStatusCode.Conflict, error);
}
}
关于c# - 返回 JSON 错误消息,IActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53625036/