使用Nancy返回包含有效Json的字符串 [英] Returning a string containing valid Json with Nancy

查看:546
本文介绍了使用Nancy返回包含有效Json的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从另一个服务收到一个包含有效JSON的字符串. 我只想用Nancy转发此字符串,还要将content-type设置为"application/json",这将使我不再需要在客户端使用$ .parseJSON(data).

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.

如果我使用Response.AsJson,它似乎会弄乱字符串中的JSON并添加转义字符. 我可以使用字符串创建Stream并设置响应类型,例如:

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?

推荐答案

我喜欢您认为应该有一个更好的方法,因为您必须使用3行代码,我认为这与Nancy有关:-)

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 :-)

我想不出一种更好"的方法,您可以使用GetBytes方法:

I can't think of a "better" way to do it, you can either do it the GetBytes way:

Get["/"] = _ =>
    {
        var jsonBytes = Encoding.UTF8.GetBytes(myJsonString);
        return new Response
            {
                ContentType = "application/json",
                Contents = s => s.Write(jsonBytes, 0, jsonBytes.Length)
            };
    };

或投射字符串"方式:

Get["/"] = _ =>
    {
        var response = (Response)myJsonString;

        response.ContentType = "application/json";

        return response;
    };

两者都做同样的事情-后者代码更少,前者更具描述性(imo).

Both do the same thing - the latter is less code, the former more descriptive (imo).

这篇关于使用Nancy返回包含有效Json的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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