【发布时间】:2012-02-07 17:08:19
【问题描述】:
我正在编写自定义 ActionFilterAttribute 并尝试将一些数据直接写入 ASP.NET MVC 3 中的输出流。我正在编写的数据就是我需要响应的所有数据,但是在写入之后我的数据后的额外数据 - 渲染视图。我正在尝试关闭OutputStream,但它仍然可以进行写作。如何关闭此流以进行写入或忽略 HTML 呈现?
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var request = filterContext.RequestContext.HttpContext.Request;
var acceptTypes = request.AcceptTypes ?? new string[] {};
var response = filterContext.HttpContext.Response;
if (acceptTypes.Contains("application/json"))
{
response.ContentType = "application/json";
Serializer.Serialize(data, response.ContentType, response.OutputStream);
}
else if (acceptTypes.Contains("text/xml"))
{
response.ContentType = "text/xml";
Serializer.Serialize(data, response.ContentType, response.OutputStream);
}
response.OutputStream.Close();
}
UPD
例如我的数据是{"Total": 42, "Now": 9000}
而我的看法是这样的
<div>
<span>The data that shouldn't be here</span>
</div>
作为回应,我得到了
{"Total": 42, "Now": 9000}
<div>
<span>The data that shouldn't be here</span>
</div>
如您所见,它不是有效的 JSON。我的目标是只发送 JSON 或 XML
【问题讨论】:
-
尝试关闭响应而不是输出流
-
@DenisPostu 当我关闭响应时,请求无法完成
-
也许您可以描述您要完成的工作以及您在响应中得到的具体内容是不需要的?
-
@ProgrammingHero 我已经更新了问题
-
好的,您正在尝试发送 JSON 响应。您是否有理由不能简单地从操作中返回
JsonResult?
标签: c# .net asp.net-mvc stream