Should I HTML encode response of my Web API

て烟熏妆下的殇ゞ 提交于 2020-02-29 17:07:49

问题


I am designing a Web API which returns JSON as the content-type, the response body could contain characters like ', ", < and >, they are valid characters in JSON. So, my question is should I do HTML encode for my Web API response body or should I leave this task to HTML client who is consuming my Web API?


回答1:


No; you must not.

You must only escape data if and when you concatenate it into a structured format.

If you return JSON like { "text": "Content by X &amp; Y" }, anyone who reads that JSON will see the literal text &amp;.
It will only work correctly for extremely broken clients who concatenate it directly into their HTML without escaping.

In short:

Never escape text except when you're about to display it




回答2:


What platform are you using? For example, Node.js, you can use restify to handle that very well. You don't need to explicitly encode the data. Therefore, please find a restful framework or component to help you out.



来源:https://stackoverflow.com/questions/18326218/should-i-html-encode-response-of-my-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!