您将需要自己添加一些代码,以处理错误并返回消息。
一种选择是使用异常过滤器并将其添加到全局或选定的控制器上,尽管此方法仅涵盖来自控制器操作方法的异常。例如,下面的过滤器会返回一个JSON对象只有当要求接受为应用程序/ JSON(否则它会让异常通过其例如可以由全局错误页面处理):
public class CustomJSONExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
if (context.HttpContext.Request.GetTypedHeaders().Accept.Any(header => header.MediaType == "application/json"))
{
var jsonResult = new JsonResult(new { error = context.Exception.Message });
jsonResult.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError;
context.Result = jsonResult;
}
}
}
services.AddMvc(opts =>
{
//Here it is being added globally.
//Could be used as attribute on selected controllers instead
opts.Filters.Add(new CustomJSONExceptionFilter());
});
另一种选择是您可以更改签名以提供更灵活的响应。然后,您可以像通常那样处理错误,然后返回用户友好的错误消息。
public IActionResult Get() {
try {
IEnumerable<MyEntity> result;
//...result populated
return new HttpOkObjectResult(result);
} catch (Exception ex) {
//You should handle the error
HandleError(ex);//the is not an actual method. Create your own.
//You could then create your own error so as not to leak
//internal information.
var error = new
{
message = "Enter you user friendly error message",
status = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError
};
Context.Response.StatusCode = error.status;
return new ObjectResult(error);
}
}
看一看答案为[这里](http://stackoverflow.com/q/31054012/5233410)问题 – Nkosi