cs0815
cs0815

Reputation: 17388

FormsAuthentication problem

I 'form authenticate' users like this in the controller:

FormsAuthentication.SetAuthCookie(User.Email, false);

(provided that the credential are valid of course).

Usually, I can access the username of the user like this in a view (I just started to use razor):

@Html.Encode(Page.User.Identity.Name)

Unfortunately, I get:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference

I presume that:

 FormsAuthentication.SetAuthCookie(User.Email, false);

did not work correctly (login and consequent redirect work fine though).

Can anyone see something wrong? Thanks!

Christian

Upvotes: 1

Views: 485

Answers (2)

ChevCast
ChevCast

Reputation: 59193

Don't use Page. You have access to User from within the view on its own.

@Html.Encode(User.Identity.Name)

Upvotes: 3

Buildstarted
Buildstarted

Reputation: 26689

You can use HttpContext.Current.User.Identity.Name. I would suggest passing the username in as part of your ViewModel though instead of escaping into Asp.Net framework territory.

Upvotes: 0

Related Questions