Possible Duplicate:
Create RSS feed in MVC4/WebAPI
I want my controller to return rss. In MVC 3, I just create a Controller
derived from Controller
, RssResult
to write rss, derived from ActionResult
, then I return it in the controller, and everything works well.
My problem is, how can I do that with Controller
derived from ApiController
?
Thanks for your help :)
----------------Update----------------
Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
List<IRss> list = new List<IRss>
{
new Product
{
Title = "Laptop",
Description = "<strong>The latest model</strong>",
Link = "/dell"
},
new Product
{
Title = "Car",
Description = "I'm the fastest car",
Link = "/car"
},
new Product
{
Title = "Cell Phone",
Description = "The latest technology",
Link = "/cellphone"
}
};
return new RssResult(list, "The best products", "Here is our best product");
}
Here is my RssResult
public class RssResult : ActionResult
{
private List<IRss> items;
private string title;
private string description;
/// <summary>
/// Initialises the RssResult
/// </summary>
/// <param name="items">The items to be added to the rss feed.</param>
/// <param name="title">The title of the rss feed.</param>
/// <param name="description">A short description about the rss feed.</param>
public RssResult(List<IRss> items, string title, string description)
{
this.items = items;
this.title = title;
this.description = description;
}
public override void ExecuteResult(ControllerContext context)
{
XmlWriterSettings settings = new XmlWriterSettings
{Indent = true, NewLineHandling = NewLineHandling.Entitize};
context.HttpContext.Response.ContentType = "text/xml";
using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.OutputStream, settings))
{
// Begin structure
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
writer.WriteElementString("title", title);
writer.WriteElementString("description", description);
writer.WriteElementString("link", context.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority));
// Individual item
items.ForEach(x =>
{
writer.WriteStartElement("item");
writer.WriteElementString("title", x.Title);
writer.WriteStartElement("description");
writer.WriteCData(x.Description);
writer.WriteEndElement();
writer.WriteElementString("pubDate", DateTime.Now.ToShortDateString());
writer.WriteElementString("link",
context.HttpContext.Request.Url.GetLeftPart(
UriPartial.Authority) + x.Link);
writer.WriteEndElement();
});
// End structure
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
Everything works well. But now, my controller changes into public class HomeController : ApiController
. Now, what should I do to make this new controller work as the old one? How should I define the new Index
method?