session value becoming null on postback and page refresh
In my webpage I'm not able to get the session variable on post back and page resfresh.
The problem is
if the page is not IsPostback then I'm able to get the session variable. But if the page postback then the error appears.
This error comes when i upload any file to server.I am using asynchfileupload to upload a image and st开发者_开发问答ore it to a session variable. and later on button click i am saving data to directory.
but it is not occuring frequently.
here is my code
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.
after somuch googling i read that when any files is adding to any sub directory or editing the webconfig will cause cause the application to restart.
if so how can i solve this..
thanks in advance.
Well, i've just tested with ASP.NET MVC, it works fine for me. What i did was craete two actions, one for setting session variable, another for creating file, so i've modified default asp.net mvc application home controller to this:
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");
}
So, when I go to AddSessionVriable, it adds something to session and index action renders that session variable to page, that i could see, that it is not gone. Then I go to create file and my session variable is still there, so that does not restart application. I'm pretty sure, that Web Forms application works the same way, may be you're loosing some exception (for example because of missing permissions) when saving file and that restarts your application.
Don't save uploaded files inside your virtual folder for the web application.
This also reduces the security risk (now, people could potentially upload an asp page, including embedded code, and access it if they can manufacture the URL (which could be dead simple)).
精彩评论