Creating an Extended Content Result for ASP.NET MVC

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);
        }
    }
Published Monday, December 14, 2009 12:11 AM by REA_ANDREW
Filed under: , ,

Comments

# 12/14/2009 Update « Go Code

Monday, December 14, 2009 12:35 AM by 12/14/2009 Update « Go Code

Pingback from  12/14/2009 Update « Go Code

# ASP.NET MVC Archived Blog Posts, Page 1

Tuesday, December 15, 2009 1:44 AM by ASP.NET MVC Archived Blog Posts, Page 1

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

Leave a Comment

(required) 
(required) 
(optional)
(required)