【问题标题】:MVC 3 Forms Authentication User.Identity.Name return falseMVC 3 表单身份验证 User.Identity.Name 返回 false
【发布时间】:2012-02-24 17:07:59
【问题描述】:

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

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

我现在很困惑……

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

我做错了什么?

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

更新

好的,看来我找到了问题!

如果我在 ActionResult 方法中调用 User.Identety.Name,它会毫无问题地返回用户名。但是如果我在返回字符串的上传方法中调用它,它就搞砸了!

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

);

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      相关资源
      最近更新 更多