从中间件发送JSON响应

时间:2017-06-08 17:48:27

标签: c# asp.net-core

这是代码:

public Task Invoke(HttpContext httpContext)
        {
            if (Http_Server.mode == 2)
                return InteractivityTask(httpContext);
            else
                return _next(httpContext);
        }

public async Task<HttpResponse> InteractivityTask(HttpContext httpContext) {

            HttpResponse response = httpContext.Response;
            string s = getResponseBody();
            response.Clear();
            MemoryStream ms = GenerateStreamFromString(s);
            response.Body = ms;
            response.ContentType = "application/json";//not sure
            }
            return response;
        }

public MemoryStream GenerateStreamFromString(string value)
        {
            return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
        }

我没有收到回复的正文,只收到了空白正文的状态代码。

1 个答案:

答案 0 :(得分:1)

试试这个:

response.Body.Write(ms.ToArray(), 0, (int)ms.Length);

而不是:

response.Body = ms;