我希望我的控制器返回rss。在MVC 3中,我只是创建一个Controller
派生自Controller
,RssResult
来编写rss,派生自ActionResult
,然后我将其返回到控制器中,一切正常
我的问题是,如何使用Controller
派生的ApiController
来做到这一点?
感谢您的帮助:)
----------------更新----------------
这是我的控制器:
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");
}
这是我的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();
}
}
}
一切都运作良好。但现在,我的控制器变为public class HomeController : ApiController
。现在,我该怎么做才能使这个新控制器像旧的一样工作?我应该如何定义新的Index
方法?
答案 0 :(得分:0)
AFAIK,即使ASP.NET MVC也没有任何内置的RssResult。你必须实现类似于下面的WebAPI的答案中提到的内容。