2012-06-14 51 views
1

當我使用Ajax調用操作方法時,正在編寫ASP.NET MVC3 Web應用程序,並且用戶身份驗證失敗(用戶未通過身份驗證)。我的電話是這樣的:使用AJAX時ASP.NET MVC用戶身份驗證失敗

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

其中makeAsyncUploader是一個單獨的js文件中的一個函數,用於處理所有AJAX內容。我試過調試應用程序,看起來沒有任何cookie會被髮送給我。有誰知道有什麼問題?

+0

顯示爲您的makeAsyncUploader函數和您的AsyncUpload conotroller操作 –

+0

您是否可以包含來自Controller的一些代碼? – learning

回答

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)', 

我希望能幫到別人

+0

正是我在尋找:) – ruffen

+0

我很高興我可以幫助:) – free4ride