表单身份验证cookie是不是持久存在或者没有通过ajax请求过去?

时间:2012-07-18 13:08:12

标签: asp.net-mvc asp.net-mvc-3 forms-authentication

我不知道为什么我的身份验证cookie消失了。我正在使用Valums Ajax Upload和其他几个ajax请求来构建用户的头像。关于cookie消失的时间非常随机。我可以上传4个文件没有问题,然后2个文件可能(在另一次登录后)。在我调用CreateAvatar方法后,似乎可能存在问题,但就像我说的那样,它不会一直发生。我错过了什么?

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);

            }

        });
    }

登录方式:

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);

控制器上传方法:

[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);
        }

创建头像方法:

[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);
            }
        }

加载头像部分:

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

0 个答案:

没有答案