1

我正在编写一个 ASP.NET MVC3 Web 应用程序,当我使用 Ajax 调用操作方法时,用户身份验证失败(用户未通过身份验证)。我的电话看起来像这样:

$(function () {
                $("#picture").makeAsyncUploader({
                    upload_url: '@Url.Action("AsyncUpload", "Profile")',
                    flash_url: '/Scripts/swfupload.swf',
                    button_image_url: '/Scripts/blankButton.png'
                });
            });

其中 makeAsyncUploader 是处理所有 AJAX 内容的单独 js 文件中的一个函数。我已经尝试调试该应用程序,看起来没有任何 cookie 随请求一起发送给我。有谁知道是什么问题?

4

1 回答 1

2

我知道这是一个很老的问题,但我今天遇到了完全相同的问题,所以我会回答它。

Firefox 的 Flash plg 中有一个错误。上传文件时不发送cookie。我的解决方案:

1) 创建新的授权属性

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class FlashAuthorizeAttribute : AuthorizeAttribute
    {
        private const string AUTH_TOKEN = "AuthenticationToken4Flash";
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            string authToken = httpContext.Request.Params[AUTH_TOKEN];
            if (authToken != null)
            {
                FormsAuthenticationTicket authForm = FormsAuthentication.Decrypt(authToken);
                if (authForm != null)
                {
                    FormsIdentity formIdentity = new FormsIdentity(authForm);
                    string[] userRoles = System.Web.Security.Roles.GetRolesForUser(formIdentity.Name);
                    GenericPrincipal userPrincipal = new GenericPrincipal(formIdentity, userRoles);
                    httpContext.User = userPrincipal;
                }
            }
            return base.AuthorizeCore(httpContext);
        }
    }

2) 控制器

   [FlashAuthorize]
    public ActionResult AsyncUpload()
    {
        HttpPostedFileBase file = Request.Files[0];
    }

3)修改你的js(formData,scriptData对我不起作用,所以我添加了一个查询字符串)

      upload_url: '@Url.Action("AsyncUpload", "Profile")' +'?AuthenticationToken4Flash=' + '@(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)',

我希望它会帮助某人

于 2012-11-11T19:49:57.093 回答