将类实现从asp.net mvc移植到asp.net mvc核心

问题描述 投票:0回答:1

我试图实现一个ActionResult的子类,它将从REST API流式传输大型JSON对象,我发现这个解决方案在堆栈溢出,但它似乎是asp.net MVC的一个实现。

public class JsonStreamingResult : ActionResult
{
    private IEnumerable itemsToSerialize;

    public JsonStreamingResult(IEnumerable itemsToSerialize)
    {
        this.itemsToSerialize = itemsToSerialize;
    }

    public override void ExecuteResult(ActionContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.ContentEncoding = Encoding.UTF8;

        JsonSerializer serializer = new JsonSerializer();

        using (StreamWriter sw = new StreamWriter(response.OutputStream))
        using (JsonTextWriter writer = new JsonTextWriter(sw))
        {
            writer.WriteStartArray();
            foreach (object item in itemsToSerialize)
            {
                JObject obj = JObject.FromObject(item, serializer);
                obj.WriteTo(writer);
                writer.Flush();
            }
            writer.WriteEndArray();
        }
    }
}

但当我在将其移植到asp.net核心MVC的过程中,我发现响应类没有ContentEncoding和OutputStream属性。

请问,任何人都可以提供所需的更改来将此类移植到asp.net核心吗?

提前致谢。

c# asp.net-mvc asp.net-core
1个回答
0
投票

OutputStream - 在ASP.NET CoreHttpResponse包含Body属性,您可以在其中编写响应。 ContentEncoding - 设置StreamWriter的编码,因为您手动将结果写入响应流。在ASP.NET MVC中,HttpResponse.ContentEncoding仅在您调用HttpResponse.Write方法时使用。

public class JsonStreamingResult : ActionResult
{
    private IEnumerable itemsToSerialize;

    public JsonStreamingResult(IEnumerable itemsToSerialize)
    {
        this.itemsToSerialize = itemsToSerialize;
    }

    public override void ExecuteResult(ActionContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";

        JsonSerializer serializer = new JsonSerializer();

        using (StreamWriter sw = new StreamWriter(response.Body, Encoding.UTF8))
        using (JsonTextWriter writer = new JsonTextWriter(sw))
        {
            writer.WriteStartArray();
            foreach (object item in itemsToSerialize)
            {
                JObject obj = JObject.FromObject(item, serializer);
                obj.WriteTo(writer);
                writer.Flush();
            }
            writer.WriteEndArray();
        }
    }
}

更新

根据source code的说法,JsonResultExecutor内部正是我所描述的,唯一的区别是它从ContentType解析编码。

© www.soinside.com 2019 - 2024. All rights reserved.