質問

ASP.NET MVC で RSS フィードを処理するにはどのようにお勧めしますか?サードパーティのライブラリを使用していますか?BCL で RSS を使用しますか?XML をレンダリングする RSS ビューを作成するだけですか?それとも全く別のものでしょうか?

役に立ちましたか?

解決

私がお勧めするのは次のとおりです。

  1. 抽象的なベースクラスのActionResultを継承するRSSResultというクラスを作成します。
  2. ExecuteResult メソッドをオーバーライドします。
  3. ExecuteResult には呼び出し側から渡された ControllerContext があり、これを使用してデータとコンテンツ タイプを取得できます。
  4. コンテンツ タイプを RSS に変更したら、(独自のコードまたは別のライブラリを使用して) データを RSS にシリアル化し、応答に書き込みます。

  5. RSS を返すコントローラー上でアクションを作成し、戻り値の型を RssResult に設定します。返したい内容に基づいてモデルからデータを取得します。

  6. その後、このアクションに対するリクエストは、選択したデータの RSS を受信します。

これはおそらく、ASP.NET MVC でリクエストに対する応答を持つ RSS を返す最も迅速で再利用可能な方法です。

他のヒント

.NET Framework は、シンデーションを処理するクラスを公開します。シンジケーションフィードなどでは、自分でレンダリングを行ったり、他の推奨 RSS ライブラリを使用したりする代わりに、フレームワークにレンダリングを任せてみてはどうでしょうか?

基本的に必要なのは次のカスタム 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);
        }
    }
}

これで、コントローラーのアクションで以下を単純に返すことができます。

return new RssActionResult() { Feed = myFeedInstance };

私のブログに完全なサンプルがあります。 http://www.developerzen.com/2009/01/11/aspnet-mvc-rss-feed-action-result/

私も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>

詳細については、チェックアウトしてください(恥知らずなプラグ) http://rickyrosario.com/blog/creating-an-rss-feed-in-asp-net-mvc

もう 1 つのクレイジーなアプローチですが、これには利点があります。それは、通常の .aspx ビューを使用して RSS をレンダリングすることです。アクション メソッドで、適切なコンテンツ タイプを設定するだけです。このアプローチの利点の 1 つは、何がレンダリングされているか、地理位置情報などのカスタム要素を追加する方法を理解しやすいことです。

繰り返しになりますが、リストされている他のアプローチの方が優れている可能性がありますが、私はそれらを使用していないだけです。;)

これは Eran Kampf と Scott Hanselman のビデオ (リンクを忘れました) から入手したものなので、ここにある他の投稿とは少しだけ異なりますが、RSS フィードの例としてコピーペーストして準備ができているので、役立つことを願っています。

私のブログから

エラン・カンプ

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);
        }
    }
}

そしてコントローラーコードも…。

    [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()));

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top