关于跨站数据提交与页面异常的处理
之前有朋友问到了这个问题,空闲时间写了这段代码,还望大虾们指正。
页面基类代码
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test
{
public class pageBase : Page
{
private readonly static string _host = "http://localhost:18447";
private bool _isallowacross = false;
/// <summary>
/// 数据提交方式,如get、post或head
/// </summary>
public string HttpMethod
{
get {
return Request.HttpMethod.ToLower();
}
}
/// <summary>
/// 获取客户上次请求的uri地址
/// </summary>
public string UrlReferrer
{
get {
return Request.UrlReferrer == null ? "" : Request.UrlReferrer.ToString();
}
}
/// <summary>
/// 是否允许站外提交数据
/// </summary>
public bool IsAllowAcross
{
set { _isallowacross = value; }
get { return _isallowacross; }
}
/// <summary>
/// 检测跨站数据提交
/// </summary>
public void CheckAcross()
{
if (!IsAllowAcross)
{
if (HttpMethod == "post" && UrlReferrer.IndexOf(_host) == -1)
{
Response.Write("禁止跨站提交数据,请求已终止!");
Response.End();
}
}
}
/// <summary>
/// 捕获异常信息
/// </summary>
/// <param name="e"></param>
protected override void OnError(EventArgs e)
{
base.OnError(e);
Response.Write(string .Format("发生一个未处理的错误,请<a href=\"{0}\">重试</a>!信息:{1}",UrlReferrer,Server.GetLastError().Message));
Response.End();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CheckAcross();
}
}
}
调用页面代码
public partial class index : pageBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (HttpMethod == "post")
{
this.lit.Text = string.Format("欢迎用户:{0}。", Request.Form["txt"]);
Response.Write(string.Format("客户上次请求Url:{0}<br/>", Request.UrlReferrer));
}
}
////默认禁止跨站数据提交,可通过重写基类OnInit事件进行开启
//protected override void OnInit(EventArgs e)
//{
// IsAllowAcross = true;
// base.OnInit(e);
//}
}