使用 Nancy 返回包含有效 Json 的字符串
我从另一个服务收到一个包含有效 JSON 的字符串。 我只想与 Nancy 转发此字符串,但还将内容类型设置为“application/json”,这将使我无需在客户端使用 $.parseJSON(data) 。
如果我使用 Response.AsJson ,它似乎会破坏字符串中的 JSON 并添加转义字符。 我可以使用字符串创建一个 Stream 并设置响应类型,例如:
Response test = new Response();
test.ContentType = "application/json";
test.Contents = new MemoryStream(Encoding.UTF8.GetBytes(myJsonString));
但想知道是否有更简单的方法?
I receive a string that contains valid JSON from another service.
I would like to just forward this string with Nancy but also set the content-type to "application/json" which will allow me to remove the need for using $.parseJSON(data) on the client side.
If I use Response.AsJson it seems to mangle the JSON in the string and adds escape characters.
I could create a Stream with the string and set the response type something like:
Response test = new Response();
test.ContentType = "application/json";
test.Contents = new MemoryStream(Encoding.UTF8.GetBytes(myJsonString));
but would like to know if there is a simpler way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看起来 Nancy 有一个很好的 Response.AsJson 扩展方法:
Looks like Nancy has got a nice Response.AsJson extension method:
我喜欢你认为应该有更好的方法,因为你必须使用 3 行代码,我认为这说明了 Nancy :-)
我想不出“更好”的方法来做到这一点,你可以要么使用 GetBytes 方式:
要么使用“转换字符串”方式:
两者都做同样的事情 - 后者代码更少,前者更具描述性(imo)。
I like that you think there should be a better way because you're having to use 3 lines of code, I think that says something about Nancy :-)
I can't think of a "better" way to do it, you can either do it the GetBytes way:
Or the "cast a string" way:
Both do the same thing - the latter is less code, the former more descriptive (imo).
这也有效:
This also works:
和你的做法差不多。你可以做
你可以在 IResponseFormatter 上创建一个扩展方法并提供你自己的 AsXXXX 帮助程序。在 0.8 版本中,响应本身将会有一些扩展,因此您可以执行诸如 WithHeader(..)、WithStatusCode() 等操作 -
Pretty much the way you do it. You could do
You could just create an extension method on IResponseFormatter and provide your own AsXXXX helper. With the 0.8 release there will be some extensions on the response it self so you can do stuff like WithHeader(..), WithStatusCode() etc-
如果模块的所有路由都返回 JSON 字符串,那么您可以在
After
挂钩中一次为所有路由设置内容类型:If all routes of your module return a JSON string, then you can set the content type in the
After
hook for all routes at once: