Clay Smith
Clay Smith

Reputation: 1079

Membership.GetUser() is returning null when app starts

I've implemented my own AccountProfile class is ASP.net MVC and it works but now I'm running into a strange problem. First off, I'm calling AccountProfile.MyProperty in the Views/Shared/_LoginPartial.cshtml. AccountProfile.MyProperty makes a call to Membership.GetUser().UserName to work. Now, when I "signup" for an account, after I'm logged in, AccountProfile.MyProperty works and renders info into the html page.

However when I stop running, change some code, and launch again, Membership.GetUser() returns null, even though I'm still logged in according to membership.

After the page fails to load, if I navigate to the /Account/Login page, Membership.GetUser() works. After it works, I can then navigate to the index page that didn't work at start, and it works.

My question is why does Membership.GetUser() return null when my page first loads up?

Thanks.

Upvotes: 3

Views: 7437

Answers (5)

user3749386
user3749386

Reputation: 11

Try this

using Microsoft.AspNet.Identity;

var id = User.Identity.GetUserId();

Upvotes: 1

user2515583
user2515583

Reputation: 11

Add [InitializeSimpleMembership] to the Controller

Example:

using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Bencsharp.BL.Services;
using Bencsharp.Mvc.Filters;
using Bencsharp.Mvc.Models;

namespace Bencsharp.Mvc.Controllers
{
    [InitializeSimpleMembership]
    public class HomeController : Controller
    {
        // ...
    }
}

Upvotes: 0

Dmytro
Dmytro

Reputation: 1600

Just came across same issue. In MVC 4, default authentication system is initialized using filter InitializeSimpleMembershipAttribute (it's pretty clear from source code of generated project). And filter is applied only to AccountController (so, once you visit login or any other page of this controller, authentication system is initialized and you can use Membership.GetUser() normally wherever you need it).

For my current project, quick and dirty solution is to have some controller, defined like this:

[InitializeSimpleMembership]
public abstract class DefaultController : Controller
{}

And deriving other controllers of my application from DefaultController, not from Controller directly. Also, this technique is nice for having commonly used properties (like dbcontext variables etc.), at one place.

Upvotes: 0

Display Name
Display Name

Reputation: 4732

Please take a look at the following posting, perhaps you having the same issue? :

Hope this helps

Upvotes: 1

Clay Smith
Clay Smith

Reputation: 1079

Alright, I found a work around the buggy Membership.GetUser() function.

HttpContext.Current.User.Identity.Name

This piece of code gets the logged in users name, and it actually appears to work. If I have any problems with it I'll report back here.

Upvotes: 2

Related Questions