2012-02-02 69 views
3

我有一个运行MVC 3(Razor)应用程序与表单身份验证。我可以在部分视图中轻松调用@ User.Identety.Name,它将返回登录用户的名称。但是,如果我叫User.Identety.Name在控制它返回null ...MVC 3表单身份验证User.Identity.Name返回false

,如果我尝试检查(User.Identity.IsAuthenticated),它总是返回空...

我现在很困惑。 ..

登录时,我调用登录方法,该方法调用SignIn方法,我在其中设置身份验证Cookie,理论上必须包含所需的所有数据。

我在做什么错?

[HttpPost] 
    public ActionResult LogOn(LogOnModel model, string returnUrl) 
    { 
     if (ModelState.IsValid) 
     { 
      if (MembershipService.ValidateUser(model.UserName, model.Password)) 
      { 
       FormsService.SignIn(model.UserName, true); 


       if (!String.IsNullOrEmpty(returnUrl)) 
       { 
        return Redirect(returnUrl); 
       } 
       else 
       { 
        return RedirectToAction("Index", "Home"); 
       } 
      } 
      else 
      { 
       ModelState.AddModelError("", "Brugernavn eller kodeordet er forkert!"); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 


public void SignIn(string userName, bool createPersistentCookie) 
     { 
      if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); 

      FormsAuthentication.SetAuthCookie(userName, true); 

     } 



    //Upload method is in an Employee Controller. 

    public string Upload(HttpPostedFileBase fileData) 
    { 

     if (User.Identity.IsAuthenticated) 
     { 
      var fileName = 
       this.Server.MapPath("~/uploads/" + HttpContext.User.Identity.Name + "/" + 
            System.IO.Path.GetFileName(fileData.FileName)); 
      fileData.SaveAs(fileName); 
     } 
     return "ok"; 
    } 

UPDATE

好看起来像我发现这个问题!

如果我在ActionResult方法中调用User.Identety.Name,它将返回没有问题的用户名。但如果我在Upload方法中调用它返回字符串,它搞砸了!

<script type="text/javascript"> 
     $(window).load(
function() { 
    $("#fileuploader").fileUpload({ 
     'uploader': '/Scripts/uploader.swf', 
     'cancelImg': '/Images/cancel.png', 
     'buttonText': 'Vælg StykListe CSV Fil', 
     'script': '@Url.Action("Upload","Solar")', 
     'folder': '/uploads', 
     'fileDesc': 'Image Files', 
     'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.csv', 
     'multi': true, 
     'auto': true 
    }); 
} 

);

回答

3

它看起来像你使用一些客户端文件上传组件。如果这个组件使用Flash,很可能Cookie不会与请求一起发送。您可以查看following blog post,其中说明了如何发送身份验证cookie值作为参数,并在服务器上重新构建令牌。这是一个similar story