문제

ASP.NET MVC에서 RSS 피드 처리를 어떻게 권장하시겠습니까?타사 라이브러리를 사용하시나요?BCL에서 RSS 항목을 사용하시나요?XML을 렌더링하는 RSS 보기를 만드시나요?아니면 완전히 다른 것인가요?

도움이 되었습니까?

해결책

제가 추천하는 내용은 다음과 같습니다.

  1. 추상적 인 기본 집단 행동 문구를 상속하는 rssresult라는 클래스를 만듭니다.
  2. ExecuteResult 메서드를 재정의합니다.
  3. ExecuteResult에는 호출자가 전달한 ControllerContext가 있으며 이를 통해 데이터와 콘텐츠 유형을 얻을 수 있습니다.
  4. 콘텐츠 유형을 rss로 변경한 후에는 데이터를 RSS로 직렬화하고(자신의 코드나 다른 라이브러리를 사용하여) 응답에 쓸 수 있습니다.

  5. RSS를 반환하려는 컨트롤러에 작업을 만들고 반환 유형을 RssResult로 설정합니다.반환하려는 항목을 기반으로 모델에서 데이터를 가져옵니다.

  6. 그러면 이 작업에 대한 요청은 귀하가 선택한 데이터의 RSS를 받게 됩니다.

이는 아마도 ASP.NET MVC의 요청에 대한 응답이 있는 rss를 반환하는 가장 빠르고 재사용 가능한 방법일 것입니다.

다른 팁

.NET 프레임워크는 신데이션을 처리하는 클래스를 노출합니다.SyndicationFeed 등그렇다면 직접 렌더링을 수행하거나 다른 제안된 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

또 다른 미친 접근 방식이지만 장점이 있는 방법은 일반 .aspx 보기를 사용하여 RSS를 렌더링하는 것입니다.작업 방법에서 적절한 콘텐츠 유형을 설정하면 됩니다.이 접근 방식의 한 가지 이점은 렌더링되는 내용과 위치정보와 같은 사용자 정의 요소를 추가하는 방법을 쉽게 이해할 수 있다는 것입니다.

그렇다면 나열된 다른 접근 방식이 더 나을 수도 있지만 아직 사용하지 않았을 뿐입니다.;)

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