خواندن RSS Feed از وب سایت دیگر در ASP.NET
اغلب اوقات این سوال براتون پیش اومده که چگونه RSS Feed ها را از یک وب سایت نمایش دهید و یا آنها را در سایت خود فراخوانی کنید..اکثر سایت ها RSS Feed های سایت های مختلف را در صفحات خود نمایش می دهند. در این مقاله نحوه انجان آن را به شما آموزش می دهیم.برای این آموزش من Community News RSS feeds یک سایت asp.net را تست می کنم.
در ابتدا Namespaces های زیر را وارد کنید.
سی شارپ:
using System; using System.Net; using System.Xml; using System.Data;
VB.ET:
Imports System Imports System.Net Imports System.Xml Imports System.Data
عملکرد های GetRSS
وظیفه GetRSS پیدا کردن و نمایش دادن RSS feed روی وب سایت می باشد. ایده کلی این است که یک Web Request و یک Web Proxy برای وب سایت ایجاد شود. Web Response دریافت شده در نهایت با استفاده از XmlTextReader خوانده می شود.
کد زیر را به همین منظور نوشتم:
private void GetRSS() { //Create a WebRequest WebRequest rssReq = WebRequest.Create("آدرس فید سایت"); //Create a Proxy WebProxy px = new WebProxy("آدرس فید سایت", true); //Assign the proxy to the WebRequest rssReq.Proxy = px; //Set the timeout in Seconds for the WebRequest rssReq.Timeout = 5000; try { //Get the WebResponse WebResponse rep = rssReq.GetResponse(); //Read the Response in a XMLTextReader XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream()); //Create a new DataSet DataSet ds = new DataSet(); //Read the Response into the DataSet ds.ReadXml(xtr); //Bind the Results to the Repeater rssRepeater.DataSource = ds.Tables[2]; rssRepeater.DataBind(); } catch(Exception ex) { throw ex; } }
VB.NET:
Private Sub GetRSS() 'Create a WebRequest Dim rssReq As WebRequest = WebRequest.Create("آدرس فید سایت") 'Create a Proxy Dim px As New WebProxy("آدرس فید سایت", True) 'Assign the proxy to the WebRequest rssReq.Proxy = px 'Set the timeout in Seconds for the WebRequest rssReq.Timeout = 5000 Try 'Get the WebResponse Dim rep As WebResponse = rssReq.GetResponse() 'Read the Response in a XMLTextReader Dim xtr As New XmlTextReader(rep.GetResponseStream()) 'Create a new DataSet Dim ds As New DataSet() 'Read the Response into the DataSet ds.ReadXml(xtr) 'Bind the Results to the Repeater rssRepeater.DataSource = ds.Tables(2) rssRepeater.DataBind() Catch ex As Exception Throw ex End Try End Sub
نمایش RSS Feed های بازیابی شده:
برای نمایش اطلاعات از ASP.Net Repeater Control استفاده می کنیم.
<asp:Repeater ID = "rssRepeater" runat = "server"> <ItemTemplate> <table style="border:solid 1px black;width:500px;font-family:Arial"> <tr> <td style=" font-weight:bold"> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl = '<%#Eval("link")%>' Text = '<%#Eval("title")%>'></asp:HyperLink> </td> </tr> <tr> <td><hr /></td> </tr> <tr> <td style="background-color:#C2D69B"> <asp:Label ID="Label1" runat="server" Text='<%#Eval("description")%>'></asp:Label> </td> </tr> </table> <br /> </ItemTemplate> </asp:Repeater>
حال میتوانید پروژه را اجرا کنید.فایل نمونه نیز ضمیمه شده است.
دیدگاهها (0)