在 ASP.NET 中通过 XML-RPC 进行 Ping(译)

译自:http://blog.madskristensen.dk/post/Ping-using-XML-RPC-in-ASPNET.aspx

很多 Blog 已经具备了 Ping 功能,当内容发生被创建或修改的时候,就会 Ping 不同的 Ping 服务,例如 Ping-o-Matic, FeedburnerTechnorati。但并不只是博客才能受惠这个 Ping 服务,所有的网站都可以用这个技术来定期发布它们的更新情况。

所有的这些服务都可以使用 XML-RPC 或它的拓展形式,因此你可以写一个 Ping 类,仅仅是用来添加 Ping 服务的 URL。我已经写了一个可以使用到 ASP.NET 应用程序中的简单静态 Ping 类。

代码:

Here is the the three methods needed to send XML-RPC pings.
有3个方法发送XML-RPC Ping

/// <summary>
/// Sends a ping to various ping services.
/// </summary>
public static void Send()
{ Execute("http://ping.feedburner.com");
Execute("http://rpc.pingomatic.com/RPC2");
}

/// <summary>
/// Creates a web request and with the RPC-XML code in the stream.
/// </summary>
private static void Execute(string url)
{ try
{ HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml";
request.Timeout = 3000;

AddXmlToRequest(request);
request.GetResponse();
} catch (Exception)
{ // Log the error.
} }

/// <summary>
/// Adds the XML to web request. The XML is the standard
/// XML used by RPC-XML requests.
/// </summary>
private static void AddXmlToRequest(HttpWebRequest request)
{ Stream stream = (Stream)request.GetRequestStream();
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.ASCII))
{ writer.WriteStartDocument();
writer.WriteStartElement("methodCall");
writer.WriteElementString("methodName", "weblogUpdates.ping");
writer.WriteStartElement("params");
writer.WriteStartElement("param");
// Add the name of your website here
writer.WriteElementString("value", "The name of your website");
writer.WriteEndElement();
writer.WriteStartElement("param");
// The absolute URL of your website - not the updated or new page
writer.WriteElementString("value", "http://www.example.com");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
} }

使用:

下载下面这个类并把它放置在 App_Code 文件夹或一个类库里。在你ASP.NET工程的任何位置你都可以使用如下的形式来调用Send方法:
PingService.Send();

因为要 ping 所有不同的服务,你可能会考虑用异步调用的形式来实现。如此实现。现在你有一个类,可以使用 XML-RPC pings 各种各样的服务了,你可以从这个列表里找 ping 服务 .

PingService.zip (816 bytes)