I had a requirement on a small home project I am working on, where I need to add some more information to a content result than was there. More specifically I had to add the status code and also have access to the response header collection. I did come across an interesting thing with this, where by accessing and adding to the response header collection in a certain way will actually raise an exception and inform you that this is only support when IIS Integrated Pipeline is enabled. I did some looking about and found a post by Phil Haack showing how he had achieved what I was looking for when he made the Download result class.
So the following causes an exception:
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = (int)StatusCode;
foreach (string s in Headers.Keys)
{
context.HttpContext.Response.Headers.Add(s,Headers[s]);
}
base.ExecuteResult(context);
}
And the following works fine, notice the subtle difference in how the header is added now:
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = (int)StatusCode;
foreach (string s in Headers.Keys)
{
context.HttpContext.Response.AddHeader(s,Headers[s]);
}
base.ExecuteResult(context);
}
So the full code implementation of the result is below.
public class ExtendedContentResult : ContentResult
{
public NameValueCollection Headers { get; set; }
public HttpStatusCode StatusCode { get; set; }
public ExtendedContentResult()
{
Headers = new NameValueCollection();
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = (int)StatusCode;
foreach (string s in Headers.Keys)
{
context.HttpContext.Response.AddHeader(s,Headers[s]);
}
base.ExecuteResult(context);
}
}