Domanda

I have my web.conf file as follows:

    <connectionStrings>
    <add name="PaDBCon" connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Pa.mdf" providerName="System.Data.SqlClient" />
  </connectionStrings>
...
<profile>
      <providers>
        <clear />
        <add name="ProfilesProvider"
             type="System.Web.Profile.SqlProfileProvider"
             connectionStringName="PaDBCon"
             applicationName="PaWeb" />
      </providers>
      <properties>
        <add name="FirstName" type="String"/>
        <add name="LastName" type="String"/>
        <add name="Site" type="String"/>
      </properties>
    </profile>

However I get an error 'The profile default provider was not found.' If I take out the providers section It creates an aspnetdb.mdf, which won't open in visual studio, but I want the providers to be stored in my Pa.mdf db with my users and roles. Any ideas on how to get profiles to save in the same DB as user accounts and Roles?

EDIT: When using

<providers>
<clear />
<add name="ProfilesProvider"
             type="System.Web.Providers.DefaultProfileProvider"
             connectionStringName="PamperDBCon"
             applicationName="PamperWeb" />
      </providers>

I get the error -- Could not load type 'System.Web.Providers.DefaultProfileProvider'.

EDIT: As an addendum to the excellent answer below. This link was helpful in adding more explanation. Helped clear up my remaining questions.

È stato utile?

Soluzione

ASP.NET MVC 4 uses the new SimpleMembershipProvider. Here's how you could add custom fields to the autogenerated template and user profile.

  1. Create a new ASp.NET MVC 4 application using the Internet Template
  2. Navigate to the ~/Models/AccountModel.cs file and add the fields to the UserProfile class:

    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
    
        // New fields added to store profile information
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Site { get; set; }
    }
    
  3. Add the new fields to the RegisterModel view model:

    public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
    
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    
        // New fields added to store profile information
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Site { get; set; }
    }
    
  4. Modify the ~/Views/Account/Register.cshtml view to allow the user entering those additional fields when registering:

    @model MvcApplication1.Models.RegisterModel
    @{
        ViewBag.Title = "Register";
    }
    
    <hgroup class="title">
        <h1>@ViewBag.Title.</h1>
        <h2>Create a new account.</h2>
    </hgroup>
    
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()
    
        <fieldset>
            <legend>Registration Form</legend>
            <ol>
                <li>
                    @Html.LabelFor(m => m.UserName)
                    @Html.TextBoxFor(m => m.UserName)
                </li>
                <li>
                    @Html.LabelFor(m => m.FirstName)
                    @Html.TextBoxFor(m => m.FirstName)
                </li>
                <li>
                    @Html.LabelFor(m => m.LastName)
                    @Html.TextBoxFor(m => m.LastName)
                </li>
                <li>
                    @Html.LabelFor(m => m.Site)
                    @Html.TextBoxFor(m => m.Site)
                </li>
                <li>
                    @Html.LabelFor(m => m.Password)
                    @Html.PasswordFor(m => m.Password)
                </li>
                <li>
                    @Html.LabelFor(m => m.ConfirmPassword)
                    @Html.PasswordFor(m => m.ConfirmPassword)
                </li>
            </ol>
            <input type="submit" value="Register" />
        </fieldset>
    }
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    
  5. Update the Register action in the AccountController so that it stores this additional information when creating anew user:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { FirstName = model.FirstName, LastName = model.LastName, Site = model.Site });
                WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    }
    
  6. Hit Ctrl+F5 to start the application and create a new user

  7. The UserProfile table in your database will be populated with the additional fields.

  8. Finally when later you need to access those properties of some user (for example the currently authenticated user):

    using (var context = new UsersContext())
    {
        UserProfile profile = context.UserProfiles.First(x => x.UserName == User.Identity.Name);
        // TODO: do something with the user profile
    }
    
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top