在MVC4/WebAPI中创建RSS订阅源
问题描述:
我正在寻找通过MVC4(和/或WebAPI)创建RSS订阅源的最佳方法。这篇文章似乎是最适用的http://www.strathweb.com/2012/04/rss-atom-mediatypeformatter-for-asp-net-webapi/。但它是在WebAPI的预发布日期中编写的。我用的NuGet把所有包了最新的,但试图建立项目扔:在MVC4/WebAPI中创建RSS订阅源
Error 2 The type or namespace name 'FormatterContext' could not be found (are you missing a using directive or an assembly reference?) G:\Code\MvcApplication-atomFormatter\MvcApplication-atomFormatter\SyndicationFeedFormatter.cs 38 129 MvcApplication_syndicationFeedFormatter
我发现了一些文章解释说,MediaTypeFormatter自公测显著改变,但我发现有关代码段所需调整的详细信息。
是否有更新的资源显示RSSFormatter的构建?
THX
答
是我写的教程针对测试版。
以下是更新为RTM版本的代码。
一个建议,如果可能的话,就是这个例子使用一个简单的“白名单”来构建RSS/Atom feed的具体类型(在这种情况下,我的Url
模型)。理想情况下,在更复杂的场景中,您可以将格式化程序设置为针对接口而不是具体类型,并让所有模型都应该作为RSS公开以实现该接口。
希望这会有所帮助。
public class SyndicationFeedFormatter : MediaTypeFormatter
{
private readonly string atom = "application/atom+xml";
private readonly string rss = "application/rss+xml";
public SyndicationFeedFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue(atom));
SupportedMediaTypes.Add(new MediaTypeHeaderValue(rss));
}
Func<Type, bool> SupportedType = (type) =>
{
if (type == typeof(Url) || type == typeof(IEnumerable<Url>))
return true;
else
return false;
};
public override bool CanReadType(Type type)
{
return SupportedType(type);
}
public override bool CanWriteType(Type type)
{
return SupportedType(type);
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
if (type == typeof(Url) || type == typeof(IEnumerable<Url>))
BuildSyndicationFeed(value, writeStream, content.Headers.ContentType.MediaType);
});
}
private void BuildSyndicationFeed(object models, Stream stream, string contenttype)
{
List<SyndicationItem> items = new List<SyndicationItem>();
var feed = new SyndicationFeed()
{
Title = new TextSyndicationContent("My Feed")
};
if (models is IEnumerable<Url>)
{
var enumerator = ((IEnumerable<Url>)models).GetEnumerator();
while (enumerator.MoveNext())
{
items.Add(BuildSyndicationItem(enumerator.Current));
}
}
else
{
items.Add(BuildSyndicationItem((Url)models));
}
feed.Items = items;
using (XmlWriter writer = XmlWriter.Create(stream))
{
if (string.Equals(contenttype, atom))
{
Atom10FeedFormatter atomformatter = new Atom10FeedFormatter(feed);
atomformatter.WriteTo(writer);
}
else
{
Rss20FeedFormatter rssformatter = new Rss20FeedFormatter(feed);
rssformatter.WriteTo(writer);
}
}
}
private SyndicationItem BuildSyndicationItem(Url u)
{
var item = new SyndicationItem()
{
Title = new TextSyndicationContent(u.Title),
BaseUri = new Uri(u.Address),
LastUpdatedTime = u.CreatedAt,
Content = new TextSyndicationContent(u.Description)
};
item.Authors.Add(new SyndicationPerson() { Name = u.CreatedBy });
return item;
}
}
我正想着为我的web api实现这个。 我希望做的最重要的一件事是做一个联合属性,所以我可以标记我的类与标题等 –
任何想法如何做到这一点与aspvnext位? –
根本不适合,aspnetvnext将完全独立于当前的Web API或当前MVC –