ASP.NET MVC의 RSS 피드
ASP.NET MVC에서 RSS 피드 처리를 어떻게 권장합니까? 타사 라이브러리를 사용하십니까? BCL에서 RSS를 사용하십니까? XML을 렌더링하는 RSS 뷰를 만드는 것입니까? 아니면 완전히 다른 것?
여기 내가 추천하는 것이 있습니다 :
- 추상 기본 클래스 ActionResult를 상속하는 RssResult라는 클래스를 작성하십시오.
- ExecuteResult 메서드를 재정의하십시오.
- ExecuteResult에는 호출자가 ControllerContext를 전달하여이를 통해 데이터 및 컨텐츠 유형을 얻을 수 있습니다.
컨텐츠 유형을 rss로 변경하면 데이터를 RSS (직접 코드 또는 다른 라이브러리를 사용하여)로 직렬화하고 응답에 쓰려고합니다.
rss를 리턴하려는 제어기에 조치를 작성하고 리턴 유형을 RssResult로 설정하십시오. 반환하려는 항목을 기반으로 모델의 데이터를 가져옵니다.
그런 다음이 작업에 대한 요청은 선택한 모든 데이터의 rss를받습니다.
아마도 rss를 반환하는 가장 빠르고 재사용 가능한 방법은 ASP.NET MVC의 요청에 대한 응답입니다.
.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 용 새 View를 만드는 간단한 방법을 사용했습니다.
<%@ 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
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.
Then again, the other approaches listed might be better, I just haven't used them. ;)
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.
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()));
}
참고URL : https://stackoverflow.com/questions/11915/rss-feeds-in-asp-net-mvc
'development' 카테고리의 다른 글
MySQL의 부울 값에 대한 부울 대 tinyint (1) (0) | 2020.07.27 |
---|---|
로직 프로그래밍과 관련하여 Prolog와 miniKanren의 주요 기술적 차이점은 무엇입니까? (0) | 2020.07.27 |
C ++ 개인 상속을 언제 사용해야합니까? (0) | 2020.07.27 |
RichTextBox (WPF)에는 문자열 속성 "Text"가 없습니다. (0) | 2020.07.27 |
EditorFor () 및 html 속성 (0) | 2020.07.27 |