未设置为对象实例的对象引用.在step
本文关键字:对象引用 step 实例 设置 对象 | 更新日期: 2023-09-27 18:18:33
我想把用户的IP和活动保存在一个名为logPublic的表中,我想当一个未经认证的用户试图访问一个特殊的文件夹,例如Admin文件夹,我可以在logPublic表中添加一个记录,它有一些字段为e,g: ID,IP,活动,日期时间。之后,未经认证的用户将被自动锁定
我使用下面的代码在Load_Page事件的主页在管理文件夹:
$public partial class Admin : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Session["IsBlocked"] = true;
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Session["UserIP"] = ip;
HttpContext.Current.Session["Activity"] = HttpContext.Current.Request.Url;
HttpContext.Current.Session["DateTime"] = System.DateTime.Now;
}
else
{
if(! HttpContext.Current.User.IsInRole("Admin"))
{
Session["BlockUser"] = true;
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Session["UserIP"] = ip;
}
}
}
}
$namespace StoreProject.Data
{
public class CustomSecurityModule :IHttpModule
{
storedbEntities StoreEnt = new storedbEntities();
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
//throw new NotImplementedException();
context.BeginRequest += new EventHandler(this.app_DoSecuriy);
}
private void app_DoSecuriy(object sender, EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
storedbEntities StoreEnt = new storedbEntities();
if (context.Session["BlockUser"]!= null && Convert.ToBoolean(context.Session["BlockUser"])== true)
{
logPrivate Log = new logPrivate()
{
Username = context.User.Identity.Name,
IP = context.Session["UserIP"].ToString(),
Enter = System.DateTime.Now,
};
StoreEnt.logPrivates.AddObject(Log);
StoreEnt.SaveChanges();
context.Response.Redirect("~/UnAuthorizedAccess.aspx");
}
//ublock != null && bool.TryParse(ublock.ToString(),out isblocked) && isblocked
else if ( context.Session["BlockPublick"] != null
&& System.Convert.ToBoolean(context.Session["BlockPublick"]) == true)
{
LogPublic newLog = new LogPublic()
{
IP = context.Session["UserIP"].ToString(),
Activity = context.Session["Activity"].ToString(),
Enter = Convert.ToDateTime(context.Session["DateTime"])
};
StoreEnt.LogPublics.AddObject(newLog);
StoreEnt.SaveChanges();
context.Response.Redirect("~/UnAuthorizedAccess.aspx");
}
}
}
}
但是当我运行我的应用程序网站时,我从httpmodule得到一个错误:对象引用未设置为对象的实例。
下行错误if (context.Session["BlockUser"]!= null
&& Convert.ToBoolean(
context.Session["BlockUser"])== true)
我没有任何记录在LogPublic表或logPrivate表,当我想要访问一个页面在管理文件夹请指引我
谢谢
Module的BeginRequest访问Session对象太早了,因为它还没有被ASP创建。净管道。您必须将逻辑移动到处理管道中稍后的事件之一(在PostAcquireRequestState
之后)