在WebAPI的null上返回空json [英] Return empty json on null in WebAPI

查看:205
本文介绍了在WebAPI的null上返回空json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当webApi返回null对象时,是否可以返回{}而不是null? 这是为了防止我的用户在解析响应时出错.并使响应成为有效的Json响应?

Is it possible to return { } instead of null when webApi returns a null object? This, to prevent my user from getting errors while parsing the response. And to make the response a valid Json Response?

我知道我可以在任何地方手动设置它.当响应为null时,应返回一个空的Json对象.但是,有没有一种方法可以针对每个响应自动执行此操作?

I know that i could be setting it everywhere manually. That when null is the response, an empty Json object should be returned. But, is there a way to do it automaticly for every response?

推荐答案

如果要构建 RESTful 服务,并且没有任何资源可返回,我相信返回 404更正确找不到),然后返回 200(确定)响应,并带有空荡荡的身体.

If you are building a RESTful service, and have nothing to return from the resource, I believe that it would be more correct to return 404 (Not Found) than a 200 (OK) response with an empty body.

这篇关于在WebAPI的null上返回空json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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