Returning a string containing valid Json with Nancy

后端 未结 5 585
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 14:05

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

5条回答
  •  一个人的身影
    2021-01-31 14:50

    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:

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

    Or the "cast a string" way:

    Get["/"] = _ =>
        {
            var response = (Response)myJsonString;
    
            response.ContentType = "application/json";
    
            return response;
        };
    

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

提交回复
热议问题