使用Nancy返回包含有效Json的字符串

Dav*_*ave 47 c# json nancy

我收到一个包含来自其他服务的有效JSON的字符串.我想用Nancy转发这个字符串,但也将内容类型设置为"application/json",这将允许我删除在客户端使用$ .parseJSON(数据)的需要.

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

Response test = new Response();
test.ContentType = "application/json";
test.Contents = new MemoryStream(Encoding.UTF8.GetBytes(myJsonString)); 
Run Code Online (Sandbox Code Playgroud)

但是想知道是否有更简单的方法?

Dar*_*ius 73

看起来Nancy有一个很好的Response.AsJson扩展方法:

Get["/providers"] = _ =>
            {
                var providers = this.interactiveDiagnostics
                                    .AvailableDiagnostics
                                    .Select(p => new { p.Name, p.Description, Type = p.GetType().Name, p.GetType().Namespace, Assembly = p.GetType().Assembly.GetName().Name })
                                    .ToArray();

                return Response.AsJson(providers);
            };
Run Code Online (Sandbox Code Playgroud)


Ste*_*ins 54

我喜欢你认为应该有一个更好的方法,因为你必须使用3行代码,我认为这是关于南希的一些内容:-)

我无法想到一个"更好"的方法,你可以采用GetBytes方式:

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

或者"投一串"的方式:

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

        response.ContentType = "application/json";

        return response;
    };
Run Code Online (Sandbox Code Playgroud)

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


小智 18

这也有效:

Response.AsText(myJsonString, "application/json");
Run Code Online (Sandbox Code Playgroud)


The*_*kie 7

几乎就是你这样做的方式.你可以做到

var response = (Response)myJsonString;
response.ContentType = "application/json";
Run Code Online (Sandbox Code Playgroud)

您可以在IResponseFormatter上创建一个扩展方法,并提供您自己的AsXXXX帮助程序.有了0.8版本,它会自动响应一些扩展,所以你可以做像WithHeader(..),WithStatusCode()等的东西 -