我正在編寫自定義ActionFilterAttribute
並試圖將一些數據直接寫入ASP.NET MVC 3的輸出流。我寫的數據是我需要作出的所有迴應,但寫完後,我的數據呈現視圖之後還有額外的數據。我正在努力關閉OutputStream
,但它仍然保持寫作的可訪問性。如何關閉此流以進行寫入或忽略HTML呈現?HttpWebResponse輸出流不關閉
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
嘗試關閉響應而不是OutputStream – DenisPostu 2012-01-11 10:24:43
@DenisPostu當我關閉響應時,請求無法完成 – 2012-01-11 10:30:11
也許你可以描述你正在嘗試完成什麼,以及你在不需要的響應中得到了什麼? – 2012-01-11 12:10:03