Aaron Blenkush
Aaron Blenkush

Reputation: 3059

Using ASP.NET SqlMembershipProvider with GUID UserID in MVC4 web application

I have an existing ASP.NET Web Forms site I'm in the process of upgrading to an ASP.NET MVC4 Web Application.

It looks like it should be possible to use my existing membership database with the SimpleMembershipProvider that MVC4 web apps use by default.

The problem is that the SimpleMembershipProvider expects the UserId column to be of type int, while my existing database uses a guid.

Here's the relevant portion of my web.config:

<membership defaultProvider="SqlMembershipProvider">
  <providers>
    <remove name="SqlMembershipProvider"/>
    <add
      name="SqlMembershipProvider"
      connectionStringName="LocalSqlServer"
      enablePasswordRetrieval="false"
      enablePasswordReset="true"
      requiresQuestionAndAnswer="false"
      requiresUniqueEmail="false"
      passwordFormat="Hashed"
      applicationName="/"
      maxInvalidPasswordAttempts="10"
      minRequiredPasswordLength="1"
      minRequiredNonalphanumericCharacters="0"
      passwordAttemptWindow="10"
      passwordStrengthRegularExpression=""
      type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
  </providers>
</membership>

Attempting to change the password, for example, I get a RuntimeBinderException:

"Cannot convert type 'System.Guid' to 'int'".

My primary question is: Ideally, I'd like to keep my existing database intact, and configure the MVC web app to work with it. How can I configure my MVC4 web app to use my existing database (with GUID UserId's) as the membership database?

As a secondary question: I suppose I could change the UserId column to int; does anybody foresee any problems with that, or know the best way to go about that?


This was the best lead I could find on using a UserId of type GUID: http://aspnet.uservoice.com/forums/41201-asp-net-mvc/suggestions/3573751-use-generic-types-for-userid-in-simple-membership-

Upvotes: 3

Views: 2601

Answers (1)

Aaron Blenkush
Aaron Blenkush

Reputation: 3059

I found a workaround:

  • Changed the provider type back to System.Web.Security.SqlMembershipProvider
  • Modify the AccountController to perform the actions using the Membership and FormsAuthentication classes instead of the WebSecurity class
  • Removed the SimpleMembershipProvider attribute from the AccountController

For example, to validate a login and set a cookie:

if (ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password)) 
{
    FormsAuthentication.SetAuthCookie(model.UserName,false);
    return RedirectToLocal(returnUrl);
}

Upvotes: 4

Related Questions