[英]Porting a class implementation from asp.net mvc to asp.net mvc core
我試圖實現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 core嗎?
提前致謝。
OutputStream-在ASP.NET Core
HttpResponse
包含可以向其寫入響應的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();
}
}
}
更新資料
根據源代碼 , JsonResultExecutor
內部完全按照我的描述進行操作,只是區別在於它解析ContentType
編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.