Friday, July 29, 2011

Using System.Web.Profile in MVC web app project

I wanted to use the System.Web.Profile class in my MVC project to store user information that is used to retrieve data. This information included user id and the current user settings. While finding plenty of examples of how to use the System.Web.Profile class, almost none of the examples mentioned that
Web Application Project (unlike Wet Site Project) doesn't support generating strongly typed ProfileCommon classes from settings in web.config
So without further ado, here is what I had to do - as detailed on the always extremely useful stackoverflow.com.
Create a new MVC model class and make it inherit from ProfileBase:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace YourNamespace
{
    public class AccountProfile : ProfileBase
    {
        static public AccountProfile CurrentUser
        {
            get { return (AccountProfile)
                         (ProfileBase.Create(Membership.GetUser().UserName)); }
        }

        public string FullName
        {
            get { return ((string)(base["FullName"])); }
            set { base["FullName"] = value; Save(); }
        }

        // add additional properties here
    }
}
Now I still had problems with the Membership.GetUser() method because even though I have authenticated the user, the membership was null. So all I needed to do is to pass the username into the CurrentUser method.

static public AccountProfile CurrentUser(string username)
        {
            get { return (AccountProfile)
                         (ProfileBase.Create(username)); }
        }

You may ask why membership was null even though I authenticated the user. This was because I am using FormsAuthentication to set the token (i.e.FormsAuthentication.SetAuthCookie()). Membership was not set at this point. It was merely used to Validate the user (i.e. Membership.ValidateUser()).

So, this article actually overcomes a combination of issues.

No comments: