Search code examples
c#asp.net-mvcasp.net-mvc-3forms-authentication

MVC 3 Forms Authentication User.Identity.Name return false


I've got a running MVC 3 (Razor) application with Forms authentication. I can easily call @User.Identety.Name in a partial view, which will return the name of logged in user. But if I call User.Identety.Name in Controller it return null...

If i try check if (User.Identity.IsAuthenticated) it always return null...

I'm confused now...

On logon, I call logon method, which calls SignIn method where I set authentication cookie, which in theory have to contain all the data I need to get.

What am I Doing Wrong?

  [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

Okay looks like i found the problem!

If i call User.Identety.Name in a ActionResult method, it returns user name without problem. but if i call it in Upload method which returns String, it mess up!

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

);


Solution

  • It looks like you are using some client side file upload component. If this component uses Flash, it is quite possible that cookies are not sent with the request. You may take a look at the following blog post which illustrates how you could send the authentication cookie value as parameter and on the server reconstruct the token. And here's a similar story.