Forms authentication cookie is not persisting or is not getting past through an ajax request?
===

I am at a loss as to why my authentication cookie disappears. I am using Valums Ajax Upload in conjunction with a couple other ajax requests to build a user's avatar. It is very random as to when the cookie disappears. I can upload 4 files without an issue, then 2 files maybe (after another login). It seems after I call the CreateAvatar method, that is where there might be an issue, but like I said, it doesn't happen all the time. What am I missing?

JavaScript:

    $(function () {
            //This is the Upload Method
            var fileCount = 0;
            var uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader'),
                action: '/Admin/Avatar/AvatarUpload',
                debug: true,
                params: {
                    'userId': '@ViewBag.UserId'
                },
                onSubmit: function (id, fileName) {
                    fileCount++;
                },
                onComplete: function (id, fileName, responseJson) {
                    if (responseJson.success) {
                        //fileCount--;
                                            if (createAvatar(responseJson.file, responseJson.imageId)) {
                                                fileCount--;
    
                                            } else {
                                                fileCount--;
                                                //alert('There was an error when trying to save ' + fileName);
                                            }
                    } else {
                        $("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
                        fileCount--;
                    }
    
                    if (fileCount == 0) {
    
                    }
    
                },
                onCancel: function (id, fileName) {
                    fileCount--;
                    if (fileCount == 0) {
                        parent.$.fn.colorbox.close();
                    }
                }
            });
        });
    
        //This Creates the Avatar Object
        function createAvatar(fileName, imageId) {
    
            var avatarUploadModel = { 
                UploadFileName: fileName,
                UserId: '@ViewBag.UserId',
                ImageId: imageId
            
            };
            $.ajax({
                url: '/Admin/Avatar/CreateAvatar/',
                type: 'POST',
                cache: false,
                timeout: 100000,
                data: JSON.stringify(avatarUploadModel),
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                error: function (xhr, status, error) {
                    alert(error + " " + status);
                },
                success: function (data) {
                    if (data.success) {
    
                        loadAvatar(data.avatarModel);
                        return true;
                    } else {
                        return false;
                    }
                }
    
            });
        }
    
        //This loads the partial to view the avatar after upload
        function loadAvatar(avatarModel) {
    
            $.ajax({
                url: '/Admin/Avatar/AvatarEdit',
                type: 'GET',
                cache: false,
                timeout: 100000,
                data: avatarModel,
                dataType: "html",
                error: function (xhr, status, error) {
                    alert(error + " " + status);
                },
                success: function (data) {
    
                    $("#avatarOriginal").html(data);
    
                }
    
            });
        }

Login Method:

    var user = _userService.GetByUserName(model.Username);
                    var authTicket = new
                        FormsAuthenticationTicket(1, //version
                                                  user.Id.ToString(), // user name
                                                  DateTime.Now,
                                                  DateTime.Now.AddMinutes(40), //Expiration
                                                  model.RememberMe, //Persistent,
                                                  user.Username);
    
                    var encTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpContext.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
    
                    
                    return Json(new {success = true, url = model.ReturnUrl}, JsonRequestBehavior.AllowGet);

Upload Method on Controller:

    [HttpPost]
            public ActionResult AvatarUpload(HttpPostedFileBase fileData)
            {
                var id = Guid.NewGuid();
                string fileName;
                var serverPath = Server.MapPath("~/Areas/Admin/TemporaryUploads/");
                if (fileData != null)
                {
                    var fileRenamed = System.IO.Path.GetFileName(id + "_" + fileData.FileName);
                    fileName = Server.MapPath("~/Areas/Admin/TemporaryUploads/" + fileRenamed);
                    fileData.SaveAs(fileName);
                }
                else
                {
                    var ajaxUploadFileData = Request["qqfile"];
                    fileName = Path.Combine(serverPath, id + "_" + Path.GetFileName(ajaxUploadFileData));
                    using (var output = System.IO.File.Create(fileName))
                    {
                        Request.InputStream.CopyTo(output);
                    }
                }
    
    
                return Json(new {success = true, file = fileName, imageId = id}, JsonRequestBehavior.AllowGet);
            }


Create Avatar Method:

    [HttpPost]
            public ActionResult CreateAvatar(AvatarModel avatarModel)
            {
               
                try
                {
                    
                    var image = new WebImage(avatarModel.UploadFileName).Resize(400, 400, true);
                    var imageFileName = Path.GetFileName(avatarModel.UploadFileName);
                    var avatar = new Domain.YogaDiVitaContext.Model.Avatar()
                                     {
                                         CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
                                         ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
                                         UserId = avatarModel.UserId,
                                         Image = new Image()
                                                     {
                                                         CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
                                                         ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
                                                         OriginalImageRelativePath = "original/" + imageFileName
                                                     }
                                     };
    
                    var user = UserService.FindById(avatarModel.UserId);
                    if (user.Avatar != null)
                        RemoveAvatar(user.Avatar);
    
                    avatar = _avatarService.Create(avatar);
    
                    user.Avatar = avatar;
                    UserService.Update(user);
    
                    var basePath = Server.MapPath("~/" + avatar.ToAvatarBasePath(GlobalVariables.AvatarPath));
                    Directory.CreateDirectory(basePath);
                    Directory.CreateDirectory(basePath + "/thumbnail");
                    Directory.CreateDirectory(basePath + "/fullsize");
                    Directory.CreateDirectory(basePath + "/original");
                    image.Save(Server.MapPath("~/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath)));
    
                    avatarModel.Width = image.Width;
                    avatarModel.Height = image.Height;
                    avatarModel.Top = image.Height*0.1;
                    avatarModel.Left = image.Width*0.9;
                    avatarModel.Right = image.Width*0.9;
                    avatarModel.Bottom = image.Height*0.9;
                    avatarModel.OriginalImagePath = "/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath);
                    
                   
                    System.IO.File.Delete(avatarModel.UploadFileName);
    
                    return Json(new {success = true, avatarModel}, JsonRequestBehavior.AllowGet);
                }
                catch (Exception exception)
                {
                    return Json(new {message = exception.Message}, JsonRequestBehavior.AllowGet);
                }
            }

Load Avatar Partial:
 

    public ActionResult AvatarEdit(AvatarModel avatarModel)
            {
                return PartialView("AvatarCropPartial", avatarModel);
            }