会话值在回发和页面刷新时变为空

本文关键字:刷新 会话 | 更新日期: 2023-09-27 17:54:55

在我的网页中,我无法在post back和页面刷新上获得会话变量。

问题是

如果页面不是IsPostback,那么我就能够获得会话变量。但是如果页面回发,则出现错误。

当我上传任何文件到服务器时出现此错误。我使用asynchfileupload上传图像并将其存储到会话变量。然后点击I am saving data to directory.

但并不经常发生。

这是我的代码

protected void AsynImageLoader_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        if (AsynImageLoader.PostedFile != null)
        {
            string extension = System.IO.Path.GetExtension(AsynImageLoader.PostedFile.FileName);
            if (extension == ".jpg" || extension == ".gif" || extension == ".jpeg" || extension == ".png")
            {
                HttpPostedFile file = AsynImageLoader.PostedFile;
                Session["TempImage"] = ReadFile(file);
            }
        }
    }

on button click

       var storedImage = Session["TempImage"] as byte[];
       String Strthumbpath = Server.MapPath("content''thumbnail''");
       if (storedImage != null)
       {
           System.Drawing.Image image = GetImage(storedImage);
           if (image != null)
           {
           image.Save(Strthumbpath + strFileName);
           }
           }
///inserting values to datbase.

在谷歌上搜索了很久之后,我发现当任何文件被添加到任何子目录或编辑webconfig时,都会导致应用程序重新启动。

如果是这样,我该如何解决这个问题?

会话值在回发和页面刷新时变为空

嗯,我刚刚用ASP测试过。. NET MVC,它对我来说很好。我所做的是创建两个动作,一个用于设置会话变量,另一个用于创建文件,所以我修改了默认的asp.net mvc应用程序的home控制器为:

  public ActionResult Index()
    {
        ViewBag.Message = Session["Sample"];            
        return View();
    }
    public ActionResult About()
    {
        return View();
    }
    public ActionResult AddSessionVariable()
    {
        Session["Sample"] = "Sample session variable";
        return RedirectToAction("Index");
    }
    public ActionResult CreateFile()
    {
        var bmp = new Bitmap(100, 100);            
        bmp.Save(Server.MapPath(string.Format(@"'Images'{0}", DateTime.Now.Ticks)));
        return RedirectToAction("Index");
    }

所以,当我去addsessionvariable,它添加了一些东西到会话和索引动作渲染会话变量到页面,我可以看到,它没有消失。然后我去创建文件,我的会话变量仍然在那里,所以这不会重新启动应用程序。我很确定,Web表单应用程序的工作方式相同,可能是你失去了一些例外(例如,因为缺少权限)保存文件时,重新启动你的应用程序。

不要将上传的文件保存在你的虚拟文件夹中。

这也降低了安全风险(现在,人们可以上传一个asp页面,包括嵌入的代码,并访问它,如果他们可以制造URL(这可能是非常简单的))。