自定义actionresult返回rss类型

2012-02-21

自定义actionresult返回rss类型

我们定义了两个类,第一个类是抽象类,第二个类继承他,并且通过枚举类型和委托来实现强类型,所以我们返回的是抽象类型,只需要实现这个抽象类型就行了。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Xml.Linq; 
 
namespace ControllersAndActions.Infrastructure { 
 
    public abstract class RssActionResult : ActionResult { 
 
    } 
 
    public class RssActionResult<T> : RssActionResult { 
      public RssActionResult(string title, IEnumerable<T> data,  
         Func<T, XElement> formatter) { 
         Title = title; 
         DataItems = data; 
         Formatter = formatter; 
     } 
     public IEnumerable<T> DataItems { get; set; } 
     public Func<T, XElement> Formatter { get; set; } 
     public string Title { get; set; } 
     public override void ExecuteResult(ControllerContext context) { 
         HttpResponseBase response = context.HttpContext.Response; 
         // set the content type of the response 
         response.ContentType = "application/rss+xml"; 
         // get the RSS content 
         string rss = GenerateXML(response.ContentEncoding.WebName); 
         // write the content to the client 
      response.Write(rss);    
        } 
 
        private string GenerateXML(string encoding) { 
 
             XDocument rss = new XDocument(new XDeclaration("1.0", encoding, "yes"),  
                new XElement("rss", new XAttribute("version", "2.0"),  
                    new XElement("channel", new XElement("title", Title),  
                        DataItems.Select(e => Formatter(e))))); 
 
             return rss.ToString(); 
        } 
    } 
}

调用方法如下

public RssActionResult RSS() { 
 
    StoryLink[] stories = GetAllStories(); 
    return new RssActionResult<StoryLink>("My Stories", stories, e => { 
        return new XElement("item", 
            new XAttribute("title", e.Title), 
            new XAttribute("description", e.Description), 
            new XAttribute("link", e.Url)); 
    }); 
}
作者:robotbird, 分类:关于代码 标签: donet mvc , 浏览(3811), 评论(1)
上一篇: mvc3通过linq to xml返回xml类型result
下一篇: 从今天开始坚持不刷技术类文章

相关文章

(1)条评论 订阅

  1. ${item.nickname} 币安 说:

    第二个类继承他,并且通过枚举类型和委托来实现强类型

1

发表评论

电子邮件用于回复通知和avatar全球唯一头像 *

*