3

I have an ASP.Net MVC 5 project that I recently migrated from MVC 4. I'm using FormsAuthentication with HTTPS and anonymous authentication, and setting a cookie using this:

FormsAuthentication.RedirectFromLoginPage(Username, false)

Authentication works, but the issue I'm having is getting the current user's name in my C# code. I can get at it fine in my view,

User.Identity.GetUserName()

but I can't get at it in the controller. HttpContext.CurrentUser doesn't exist, and this.User in the controller is always null. I've also tried requesting the cookie, but it fails.

Will I have to set the Identity myself when they sign on? I may need user rolls, but I could always query the database to get them.

In short, how can I get the current user's username in my controller in MVC 5? Thanks

6
  • Forms Authentication or Identity? They are two different things. Commented Nov 20, 2014 at 20:53
  • I'm using forms authentication, not identity. I figured identity was something you could use to store user info, but I guess not. Commented Nov 20, 2014 at 20:55
  • This answer seemed to do the trick. You'll have to import WebMatrix.WebData; as well. If the user isn't authenticated it returns an empty string. stackoverflow.com/a/17254386/4051272 Commented Nov 20, 2014 at 21:09
  • 2
    Shouldn't you be calling FormsAuthentication.SetAuthCookie(Username, false) instead? That creates the cookie and usually allows using User.Identity.Name later on. Commented Nov 20, 2014 at 22:04
  • I read somewhere RedirectFromLoginPage sets a cookie for you, but I checked on another controller and can get at User.Identity now. My problem was that I was posting to the home controller, then calling another controller's method like this (new MyController()).MyMethod(myModel);. Time to change that lol. Thanks for bringing that up, I never woulda figured that out. Commented Nov 21, 2014 at 14:16

1 Answer 1

8
string cookieName = FormsAuthentication.FormsCookieName; //Find cookie name
HttpCookie authCookie = HttpContext.Request.Cookies[cookieName]; //Get the cookie by it's name
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); //Decrypt it
string UserName = ticket.Name; //You have the UserName!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.