-->

Membership.GetUser() is returning null when app st

2019-07-06 23:06发布

问题:

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.

回答1:

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.



回答2:

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

  • FormsAuthentication Membership.GetUser() Null
  • Get current MembershipUser in Forms Authentication

Hope this helps



回答3:

Try this

using Microsoft.AspNet.Identity;

var id = User.Identity.GetUserId();


回答4:

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.



回答5:

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
    {
        // ...
    }
}