我需要在不对对象进行序列化的情况下从Azure函数流式传输JSON,因为序列化开销太高。 代码可以归结为这样:
[FunctionName("AzureFunction")]
public static async Task<IActionResult>
Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/function")], HttpRequest req, ILogger log)
{
MemoryStream outputStream = new MemoryStream();
StreamWriter writer = new StreamWriter(outputStream);
JsonWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("Property");
jsonWriter.WriteValue("Value");
jsonWriter.WriteEndObject();
outputStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(outputStream, "application/json");
}
但是,此JSON在某些时候被击中之前已被转换为字符串。我已经能够将来自另一个HTTP调用的流直接传递到FileStreamResult对象,并且该对象不会转换为字符串,因此我确定这是可能的。
答案 0 :(得分:3)
我知道了,返回之前需要刷新Stream。正确的代码如下所示:
[FunctionName("AzureFunction")]
public static async Task<IActionResult>
Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/function")], HttpRequest req, ILogger log)
{
MemoryStream outputStream = new MemoryStream();
StreamWriter writer = new StreamWriter(outputStream);
JsonWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("Property");
jsonWriter.WriteValue("Value");
jsonWriter.WriteEndObject();
jsonWriter.Flush(); // Flush the json before returning.
outputStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(outputStream, "application/json");
}