编程语言
首页 > 编程语言> > c#-MVC 3表单身份验证User.Identity.Name返回false

c#-MVC 3表单身份验证User.Identity.Name返回false

作者:互联网

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

如果我尝试检查(User.Identity.IsAuthenticated)是否始终返回null …

我现在很困惑…

登录时,我调用登录方法,该方法调用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";
    }

更新

好的,看来我发现了问题!

如果我在ActionResult方法中调用User.Identety.Name,它将返回用户名,而不会出现问题.但是,如果我在返回String的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
    });
}

);

解决方法:

您似乎正在使用某些客户端文件上传组件.如果此组件使用Flash,则很有可能没有随请求一起发送Cookie.您可以看一下following blog post,它说明了如何发送身份验证cookie值作为参数以及如何在服务器上重建令牌.这是similar story.

标签:forms-authentication,c,asp-net-mvc,asp-net-mvc-3
来源: https://codeday.me/bug/20191201/2083435.html