调用Create()时,配置文件提供程序MVC4始终返回null

时间:2013-01-09 05:04:37

标签: asp.net-mvc asp.net-membership

的Web.config:

<profile enabled="true" defaultProvider="DefaultProfileProvider">
  <providers>
    <add name="DefaultProfileProvider" inherits="XCSN.Models.WebProfile" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
  </providers>
</profile>

创建用户,尝试在配置文件中分配firstname和lastname属性:

    [Authorize(Roles = "Manager")]
    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus;

            Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

            if (createStatus == MembershipCreateStatus.Success)
            {
                Roles.AddUserToRole(model.UserName, model.Role);

                //add profile information
                var profile = WebProfile.GetProfile(model.UserName);
                profile.FirstName = model.FirstName;
                profile.LastName = model.LastName;
                profile.Save();

                return RedirectToAction("Index", "Account");
            }
            else
            {
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
        }

        ViewBag.RolesList = Roles.GetAllRoles().Select(x => new SelectListItem { Text = x, Value = x });
        // If we got this far, something failed, redisplay form
        return View(model);
    }


public class WebProfile : ProfileBase
{
    [Display(Name = "First Name")]
    public virtual string FirstName
    {
        get
        {
            return (this.GetPropertyValue("FirstName").ToString());
        }
        set
        {
            this.SetPropertyValue("FirstName", value);
        }
    }

    [Display(Name = "Last Name")]
    public virtual string LastName
    {
        get
        {
            return (this.GetPropertyValue("LastName").ToString());
        }
        set
        {
            this.SetPropertyValue("LastName", value);
        }
    }

    public static WebProfile GetProfile(string username)
    {
        return Create(username) as WebProfile;
    }
}

它在这一行失败:profile.FirstName = model.FirstName; WebProfile.GetProfile(model.UserName);返回null,我不明白为什么。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

inherits =“XCSN.Models.WebProfile”应该在标签中,而不是标签。

像这样:

<profile inherits="XCSN.Models.WebProfile" enabled="true" defaultProvider="DefaultProfileProvider">
  <providers>
    <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
  </providers>
</profile>