ASP.Net核心错误JSON [英] ASP.Net Core Error JSON

查看:59
本文介绍了ASP.Net核心错误JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Core.我正在创建一个基本的webapi. 我想在出现问题时显示JSON错误.

I'm playing a bit with ASP.NET Core. I'm creating a basic webapi. I'd like to show a JSON error when there is a problem.

屏幕上显示我想要的打印屏幕. 唯一的问题是,它以200的状态码发送.

The printscreen shows want I want on my screen. The only problem is that it's send with a statuscode of 200.

catch (NullReferenceException e)
{
    return Json(NotFound(e.Message));
}

我可以通过以下方法解决它:

I could solve it by doing this:

return NotFound(new JsonResult(e.Message) {StatusCode = 404);

但是我不喜欢这样,因为现在您可以使用NotFound指定状态码500.

But I don't like this because now you can specify statuscode 500 with a NotFound.

有人可以把我带到正确的方向吗?

Can someone put me in the correct direction?

此致, 布莱希特(Brecht)

Sincerely, Brecht

推荐答案

您不能执行return NotFound(e.Message);

或者您可能有自己的错误文档格式,并选择return NotFound(new ErrorDocument(e.message));

Or you might have your own error document format and go for return NotFound(new ErrorDocument(e.message));

如果必须返回JsonResult,请执行以下操作:

If you have to return with a JsonResult then go for something like the following:

return new JsonResult(YourObject) { StatusCode = (int)HttpStatusCode.NotFound };

现在,您可以完全控制响应格式和状态代码.如果需要,您甚至可以附加序列化程序设置. :)

Now you have full control over response format and your status code too. You can even attach serializer settings if need be. :)

这篇关于ASP.Net核心错误JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆