简体   繁体   中英

Object reference not set to an instance of an object. in HttpModule

I want save users's IPs and activity in a table named logPublic,I want when a unAthenticated user try to access a speacial folder eg Admin folder i can add a record in logpublic table that it have some fields for e,g : ID,IP,Activity,datetime .after that unathenticated user will be lock utomatically

I am use below code in Load_Page Event of masterpage in Admin folder:

$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");
        }


        }
    }
}

but when i run my application website ,i get an error from httpmodule :Object reference not set to an instance of an object. error in below line

if (context.Session["BlockUser"]!= null 
  &&  Convert.ToBoolean(
        context.Session["BlockUser"])== true)

i dont have any record in LogPublic table or logPrivate table when i want visit a page in Admin Folder please guide me

thanks

Module's BeginRequest is too early to access the Session object as it hasn't been yet created by the ASP.NET Pipeline. You'd have to move your logic to one of later events in the processing pipeline (after PostAcquireRequestState )

http://msdn.microsoft.com/en-us/library/ms178473.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM