MVC ActionResult inheritance

by OfirYaron 7/19/2009 5:47:00 AM

MVC contains a nice class you can inherit inorder to return http responses other then a regular Render View:

bellow are three implementations I use the most:

ImageResult, TextResult and RssResult:

public class ImageResult : ActionResult

{

public Stream ImageStream { get; private set; }

public string ContentType { get; private set; }

public ImageResult(Stream imageStream, string contentType)

{

if (imageStream == null)

throw new ArgumentNullException("imageStream");

if (contentType == null)

throw new ArgumentNullException("contentType");

this.ImageStream = imageStream;this.ContentType = contentType;

}

public override void ExecuteResult(ControllerContext context)

{

if (context == null)

throw new ArgumentNullException("context");

HttpResponseBase response = context.HttpContext.Response;response.ContentType =

this.ContentType;

byte[] buffer = new byte[4096];

while (true)

{

int read = this.ImageStream.Read(buffer, 0, buffer.Length);

if (read == 0)

break;

response.OutputStream.Write(buffer, 0, read);

}

response.End();

}

}

public class TextResult : ActionResult

{

public string Content { get; private set; }
public TextResult(string content)

{

this.Content = content;

}

public override void ExecuteResult(ControllerContext context)

{

if (context == null)

throw new ArgumentNullException("context");HttpResponseBase response = context.HttpContext.Response;

response.Write(Content);

response.End();

}

public class RssResult : ActionResult

{

public SyndicationFeed Feed { get; set; }

public RssResult() { }

public RssResult(SyndicationFeed feed)

{

this.Feed = feed;

}

public override void ExecuteResult(ControllerContext context)

{

context.HttpContext.Response.ContentType =
"application/rss+xml";

Rss20FeedFormatter formatter = new Rss20FeedFormatter(this.Feed);

using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))

{

formatter.WriteTo(writer);

}

}

}

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

MVC

Powered by BlogEngine.NET 1.3.0.0
Theme by Mads Kristensen

About the author

Name of author Author name
Something about me and what I do.

E-mail me Send mail

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

Recent posts

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Sign in