[BlogEngine扩展]IP2Area
该插件将评论者的IP转为地区,数据取自于http://www.ip138.com
在这里表示感谢!
该扩展要在CommentAdded事件上进行处理,首先添加一个字段UserArea用来保存地区。
放心,这里的是异步处理的,不会造成页面的明显延迟。
代码如下:
/// <summary>
///Ip2Area 的摘要说明
/// </summary>
///
[Extension("IP转为地区", "1.0", "JasonYi")]
public class Ip2Area
{
public Ip2Area()
{
Post.CommentAdded += new EventHandler<EventArgs>(Post_CommentAdded);
}
void Post_CommentAdded(object sender, EventArgs e)
{
Comment p = sender as Comment;
if(p!=null)
new HttpAsyncGetIPArea(p,"http://www.ip138.com/ips.asp").Execute();
}
}
public class HttpAsyncGetIPArea
{
private Comment _comment;
private string _url;
public HttpAsyncGetIPArea(Comment c,string url)
{
_comment = c;
_url = url;
}
public Comment comment
{
get { return _comment; }
}
private HttpWebRequest Request;
public void Execute()
{
Request = (HttpWebRequest)WebRequest.Create(_url);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Byte[] data = System.Text.Encoding.ASCII.GetBytes("action=2&ip=" + _comment.IP);
Request.ContentLength = data.Length;
using (Stream stream = Request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
Request.BeginGetResponse(ProcessRespose, this);
}
private void ProcessRespose(IAsyncResult async)
{
HttpAsyncGetIPArea item = (HttpAsyncGetIPArea)async.AsyncState;
try
{
using (HttpWebResponse response = (HttpWebResponse)item.Request.EndGetResponse(async))
{
string RStr = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
RStr = sr.ReadToEnd();
}
Regex reg = new Regex(@"本站主数据:([^<li>]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
MatchCollection mc = reg.Matches(RStr);
string area = string.Empty;
if (mc.Count > 0)
{
area = mc[0].Value.Replace("本站主数据:", string.Empty);
}
if (!string.IsNullOrEmpty(area))
{
string sql = "UPDATE be_PostComment SET UserArea=@Area WHERE PostCommentID=@Id";
SqlParameter[] para = { new SqlParameter("@Area", area), new SqlParameter("@Id", comment.Id) };
SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, System.Data.CommandType.Text, sql, para);
comment.UserArea = area;
}
}
}
catch (Exception ex)
{
//throw new System.Net.WebException("Get HttpResponse Error");
}
finally
{
Request.Abort();
}
}
}
坐个沙发^_^