asp.net-mvc ASP.NET MVC 中的 RSS 提要

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 22:43:51  来源:igfitidea点击:

RSS Feeds in ASP.NET MVC

asp.net-mvcrss

提问by Lance Fisher

How would you reccommend handling RSS Feeds in ASP.NET MVC? Using a third party library? Using the RSS stuff in the BCL? Just making an RSS view that renders the XML? Or something completely different?

您建议如何在 ASP.NET MVC 中处理 RSS 提要?使用第三方库?在 BCL 中使用 RSS 内容?只是制作一个呈现 XML 的 RSS 视图?或者完全不同的东西?

采纳答案by Dale Ragan

Here is what I recommend:

这是我推荐的:

  1. Create a class called RssResult that inherits off the abstract base class ActionResult.
  2. Override the ExecuteResult method.
  3. ExecuteResult has the ControllerContext passed to it by the caller and with this you can get the data and content type.
  4. Once you change the content type to rss, you will want to serialize the data to RSS (using your own code or another library) and write to the response.

  5. Create an action on a controller that you want to return rss and set the return type as RssResult. Grab the data from your model based on what you want to return.

  6. Then any request to this action will receive rss of whatever data you choose.

  1. 创建一个名为 RssResult 的类,该类继承了抽象基类 ActionResult。
  2. 覆盖 ExecuteResult 方法。
  3. ExecuteResult 将 ControllerContext 由调用者传递给它,这样您就可以获得数据和内容类型。
  4. 将内容类型更改为 rss 后,您需要将数据序列化为 RSS(使用您自己的代码或其他库)并写入响应。

  5. 在要返回 rss 的控制器上创建一个操作,并将返回类型设置为 RssResult。根据您想要返回的内容从您的模型中获取数据。

  6. 然后,对此操作的任何请求都将收到您选择的任何数据的 rss。

That is probably the quickest and reusable way of returning rss has a response to a request in ASP.NET MVC.

这可能是在 ASP.NET MVC 中返回 rss 响应请求的最快和可重用方式。

回答by Eran Kampf

The .NET framework exposes classes that handle syndation: SyndicationFeed etc. So instead of doing the rendering yourself or using some other suggested RSS library why not let the framework take care of it?

.NET 框架公开了处理联合的类:SyndicationFeed 等。所以与其自己进行渲染或使用其他一些建议的 RSS 库,为什么不让框架来处理它呢?

Basically you just need the following custom ActionResult and you're ready to go:

基本上,您只需要以下自定义 ActionResult 就可以了:

public class RssActionResult : ActionResult
{
    public SyndicationFeed Feed { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "application/rss+xml";

        Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed);
        using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
        {
            rssFormatter.WriteTo(writer);
        }
    }
}

Now in your controller action you can simple return the following:

现在在您的控制器操作中,您可以简单地返回以下内容:

return new RssActionResult() { Feed = myFeedInstance };

There's a full sample on my blog at http://www.developerzen.com/2009/01/11/aspnet-mvc-rss-feed-action-result/

我的博客上有一个完整的示例,网址http://www.developerzen.com/2009/01/11/aspnet-mvc-rss-feed-action-result/

回答by Ricky

I agree with Haacked. I am currently implementing my site/blog using the MVC framework and I went with the simple approach of creating a new View for RSS:

我同意 Haacked。我目前正在使用 MVC 框架实现我的网站/博客,我采用了为 RSS 创建新视图的简单方法:

<%@ Page ContentType="application/rss+xml" Language="C#" AutoEventWireup="true" CodeBehind="PostRSS.aspx.cs" Inherits="rr.web.Views.Blog.PostRSS" %><?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>ricky rosario's blog</title>
<link>http://<%= Request.Url.Host %></link>
<description>Blog RSS feed for rickyrosario.com</description>
<lastBuildDate><%= ViewData.Model.First().DatePublished.Value.ToUniversalTime().ToString("r") %></lastBuildDate>
<language>en-us</language>
<% foreach (Post p in ViewData.Model) { %>
    <item>
    <title><%= Html.Encode(p.Title) %></title>
    <link>http://<%= Request.Url.Host + Url.Action("ViewPostByName", new RouteValueDictionary(new { name = p.Name })) %></link>
    <guid>http://<%= Request.Url.Host + Url.Action("ViewPostByName", new RouteValueDictionary(new { name = p.Name })) %></guid>
    <pubDate><%= p.DatePublished.Value.ToUniversalTime().ToString("r") %></pubDate>
    <description><%= Html.Encode(p.Content) %></description>
    </item>
<% } %>
</channel>
</rss>

For more information, check out (shameless plug) http://rickyrosario.com/blog/creating-an-rss-feed-in-asp-net-mvc

有关更多信息,请查看(无耻插件)http://rickyrosario.com/blog/creating-an-rss-feed-in-asp-net-mvc

回答by Haacked

Another crazy approach, but has its advantage, is to use a normal .aspx view to render the RSS. In your action method, just set the appropriate content type. The one benefit of this approach is it is easy to understand what is being rendered and how to add custom elements such as geolocation.

另一种疯狂的方法,但有其优势,是使用普通的 .aspx 视图来呈现 RSS。在您的操作方法中,只需设置适当的内容类型。这种方法的一个好处是很容易理解正在呈现的内容以及如何添加自定义元素,例如地理定位。

Then again, the other approaches listed might be better, I just haven't used them. ;)

再说一次,列出的其他方法可能更好,我只是没有使用它们。;)

回答by TheDev6

I got this from Eran Kampf and a Scott Hanselman vid (forgot the link) so it's only slightly different from some other posts here, but hopefully helpful and copy paste ready as an example rss feed.

我从 Eran Kampf 和 Scott Hanselman 视频(忘记链接)那里得到了这个,所以它与这里的其他一些帖子略有不同,但希望有帮助,并准备好复制粘贴作为示例 RSS 提要。

From my blog

从我的博客

Eran Kampf

伊兰·坎普夫

using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace MVC3JavaScript_3_2012.Rss
{
    public class RssFeed : FileResult
    {
        private Uri _currentUrl;
        private readonly string _title;
        private readonly string _description;
        private readonly List<SyndicationItem> _items;

        public RssFeed(string contentType, string title, string description, List<SyndicationItem> items)
            : base(contentType)
        {
            _title = title;
            _description = description;
            _items = items;
        }

        protected override void WriteFile(HttpResponseBase response)
        {
            var feed = new SyndicationFeed(title: this._title, description: _description, feedAlternateLink: _currentUrl,
                                           items: this._items);
            var formatter = new Rss20FeedFormatter(feed);
            using (var writer = XmlWriter.Create(response.Output))
            {
                formatter.WriteTo(writer);
            }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            _currentUrl = context.RequestContext.HttpContext.Request.Url;
            base.ExecuteResult(context);
        }
    }
}

And the Controller Code....

和控制器代码....

    [HttpGet]
public ActionResult RssFeed()
{
    var items = new List<SyndicationItem>();
    for (int i = 0; i < 20; i++)
    {
        var item = new SyndicationItem()
        {
            Id = Guid.NewGuid().ToString(),
            Title = SyndicationContent.CreatePlaintextContent(String.Format("My Title {0}", Guid.NewGuid())),
            Content = SyndicationContent.CreateHtmlContent("Content The stuff."),
            PublishDate = DateTime.Now
        };
        item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri("http://www.google.com")));//Nothing alternate about it. It is the MAIN link for the item.
        items.Add(item);
    }

    return new RssFeed(title: "Greatness",
                       items: items,
                       contentType: "application/rss+xml",
                       description: String.Format("Sooper Dooper {0}", Guid.NewGuid()));

}