如何在单个会话变量中存储和检索多个值

how to store and retrieve multiple values inside single session variable

我正在使用 dropzone 将多个文件上传到服务器。文件将上传到服务器,而文件名将存储在 table.

我正在尝试在会话中添加文件名。 这里的问题是它不会在单个会话中添加多个文件名

这是我的代码:

string imageSessList = context.Session["imageNames"].ToString();  //if i put this line at the begining, then the debugger doesn't even moves to foreach block


    foreach (string s in context.Request.Files)
    {
        HttpPostedFile file = context.Request.Files[s];
        string fileName = file.FileName;
        string fileExtension = file.ContentType;
        string strUploadFileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
        string strAllowedFileTypes = "***jpg***jpeg***png***gif***bmp***"; //allowed file types
        string destFileName = "";
        List<string> lstImageNames = new List<string>();




        // else upload file
        if (!string.IsNullOrEmpty(fileName))
        {
            if (strAllowedFileTypes.IndexOf("***" + strUploadFileExtension + "***") != -1) //check extension
            {
                if (context.Request.Files[0].ContentLength < 5 * 1024 * 1024) //check filesize
                {
                    // generate file name
                    destFileName = Guid.NewGuid().ToString() + "." + strUploadFileExtension;
                    string destFilePath = HttpContext.Current.Server.MapPath("/resourceContent/") + destFileName;
                    //Save image names to session
                    lstImageNames.Add(destFileName);
                    context.Session["imageNames"] = lstImageNames;
                    file.SaveAs(destFilePath);

                    strMessage = "Success " + destFileName;
                }
                else
                {
                    strMessage = "File Size can't be more than 5 MB.";
                }
            }
            else
            {
                strMessage = "File type not supported!";
            }
        }
    } // foreach
context.Response.Write(strMessage);
}

这里我只能将单个文件名添加到会话中,不能添加多个。

如何在单个会话中存储和维护多个文件名: context.Session["imageNames"]

您需要从会话中获取当前列表

 List<string> lstImageNames= (List<string>)Session["imageNames"];
 if(lstImageNames==null)
     lstImageNames = new List<string>(); // create new list in the first time

现在向其中添加新项目。

 lstImageNames.Add(destFileName);

返回会话

 context.Session["imageNames"] = lstImageNames;