views:

724

answers:

3

I'm working with a custom asp.net membership provider in conjunction with the default Account controller that comes with the asp.net MVC example app. Everything is going smoothly except for one tiny thing: After a user creates an account and is automatically logged in and redirected, their username is not displayed with the usual welcome message.

I thought perhaps this was because they were not logged in at the time they made the request. Once they log in again their name appears at the top, so I don't think it's the membership providers fault, but I could be wrong.

The register and redirect controller method that ships with asp.net MVC looks like this:

public ActionResult Register(string userName, string email, string password, string confirmPassword)
{

    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

    if (ValidateRegistration(userName, email, password, confirmPassword))
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);

        if (createStatus == MembershipCreateStatus.Success)
        {
            FormsAuth.SignIn(userName, false /* createPersistentCookie */);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
        }
    }

    // If we got this far, something failed, redisplay form
    return View();
}

This is using forms authentication by the way.

Edit: Here is the Master page used by the Index page. It's the Site.master that ships with the default asp.net MVC application:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

    <div id="header">
        <div id="title">
            <h1>Internship Site</h1>
        </div>

        <div id="logindisplay">
            <% Html.RenderPartial("LogOnUserControl"); %>
        </div> 

        <div id="menucontainer">

            <ul id="menu">              
                <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                <li><%= Html.ActionLink("About", "About", "Home")%></li>
            </ul>

        </div>
    </div>

    <div id="main">
        <noscript>Your browser does not support JavaScript!</noscript>
        <asp:ContentPlaceHolder ID="MainContent" runat="server" />

        <div id="footer">
        </div>
    </div>
</div>

Any help and insight greatly appreciated.

+1  A: 

You're correct. The reason it's not showing the user's name is because they are not logged in at the time of the redirect to the homepage after account creation. Change the following line:

FormsAuth.SignIn(userName, false /* createPersistentCookie */);

to:

FormsAuth.SignIn(userName, true /* createPersistentCookie */);
MunkiPhD
Even when I create the cookie I get the same result.
Graham
Check your cookies then. Have you tried doing this workflow with cleaned out cookies?
MunkiPhD
Yes, I clear them before each test.
Graham
I take it you've stepped through the code - That's a very weird issue. The only thing I can think of is to try a brand new project and don't change a thing in it. Then run it. If you have the same issue, then there's something else going on and you can eliminate the code from being the issue. It could be browser settings or some other peculiar factor that is causing an error somewhere, yet not being reported.
MunkiPhD
It works now, inexplicably!I had traced through it before and everything seemed fine, I took your suggestion and opened a new project and tested that, everything worked fine. When I reopened mine it too worked.I have no idea what would cause this behavior, but since your suggestion lead to me finding the "solution" I'm marking it as the answer. : )
Graham
this doesnt seem like a good suggestion to me unless you want the login to persist even when the browser has closed
Simon_Weaver
A: 

I do (instead of FormsAuth.SignIn())

if (Provider.ValidateUser(username, password)   
{  
     FormsAuth.SetAuthCookie(username, rememberMe);  
}

where remember me is a variable indicating the value of the remember me checkbox (true, false)

Edit: I just saw that this is in registration. I still use the .SetAuthCookie, but obviously I don't do the .ValidateUser (in my registration code).

Russell Steen
This produces the same result unfortunately.
Graham
can you show the code for home index that you are redirecting to?
Russell Steen
I have added the master page used by the index view to my original post. The view itself is just placeholder stuff.
Graham
Sorry, I meant the code for the action. I was not very clear there. Let me look into my project some more and I'll see what I can find out. Let us know if you solve it.
Russell Steen
Oh OK, sorry, the code for the home controller index action that it redirects to is like this:public ActionResult Index(){ ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View();}
Graham
A: 

The normal process of user validation and automated login goes as following:

        public ActionResult Login(string userName, string password, bool persistent, string returnUrl)
    {

        if (returnUrl != null && returnUrl.IndexOf("/user/login", StringComparison.OrdinalIgnoreCase) >= 0)
            returnUrl = null;

        if (Membership.ValidateUser(userName, password))
        {
            FormsAuthentication.SetAuthCookie(userName, persistent);

            if (!String.IsNullOrEmpty(returnUrl))
                return this.Redirect(303, returnUrl);
            else
                return this.Redirect(303, FormsAuthentication.DefaultUrl);
        }
        else
            TempData["ErrorMessage"] = "Login failed! Please make sure you are using the correct user name and password.";
        return View();
    }
Sergej Kravcenko