Membership.GetUser() is returning null when app st

2019-07-06 22:21发布

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.

5条回答
Fickle 薄情
2楼-- · 2019-07-06 23:01

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

Hope this helps

查看更多
倾城 Initia
3楼-- · 2019-07-06 23:02

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.

查看更多
该账号已被封号
4楼-- · 2019-07-06 23:18

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.

查看更多
干净又极端
5楼-- · 2019-07-06 23:20

Try this

using Microsoft.AspNet.Identity;

var id = User.Identity.GetUserId();
查看更多
ゆ 、 Hurt°
6楼-- · 2019-07-06 23:20

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
    {
        // ...
    }
}
查看更多
登录 后发表回答