我最近问这个问题如何持久是anon用户选择(前:主题选择)。并开始了解ASP.NET配置文件及其在Web配置中的属性。我从链接中尝试了答案,但我无法访问profile.newproperty

如何分配配置文件值? 此问题指定Web-Applications不支持配置文件框中,并且必须创建基于ProfileBase的自定义模型。问题是在2009年回答,我想知道这仍然是相同的案例。

在ASP.NET 4.0 Web应用程序中可以访问Profile.NewProperty与在Web.config中的部分中定义的属性,而无需代码C#,除了访问它时。

有帮助吗?

解决方案

我只是看到了你的问题,是的,你是对的,我发布的答案与网站有关,因此,它不适用于Web应用程序或MVC

在这里,我将显示使用匿名和经过身份验证的用户配置文件在MVC中使用配置文件的代码

输出

匿名用户 - 没有配置文件集但

匿名用户 - 配置文件集

经过身份验证的用户 - 配置文件迁移

web.config

<anonymousIdentification enabled="true"/>
<profile inherits="ProfileInWebApplicationMVC1.UserProfile">
  <providers>
    <clear/>
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
  </providers>
</profile>
.

userprofile类

public class UserProfile : ProfileBase
{
    public static UserProfile GetProfile()
    {
        return HttpContext.Current.Profile as UserProfile;
    }

    [SettingsAllowAnonymous(true)]
    public DateTime? LastVisit
    {
        get { return base["LastVisit"] as DateTime?; }
        set { base["LastVisit"] = value; }
    }

    public static UserProfile GetProfile(string userID)
    {
        return ProfileBase.Create(userID) as UserProfile;
    }
}
.

主控制器

    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        var p = UserProfile.GetProfile();

        return View(p.LastVisit);
    }

    [HttpPost]
    public ActionResult SaveProfile()
    {
        var p = UserProfile.GetProfile();

        p.LastVisit = DateTime.Now;
        p.Save();

        return RedirectToAction("Index");
    }
.

索引视图

@if (!this.Model.HasValue)
{
    @: No profile detected
}
else
{
    @this.Model.Value.ToString()
}

@using (Html.BeginForm("SaveProfile", "Home"))
{
    <input type="submit" name="name" value="Save profile" />
}
.

最后,当您是一个匿名用户时,您可以拥有自己的个人资料但是,一旦您注册到网站,您需要迁移您当前的配置文件与您的新帐户一起使用。这是因为ASP.NET成员资格,当用户登录时创建新的配置文件 - IN

global.asax,迁移配置文件的代码

    public void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs args)
    {
        var anonymousProfile = UserProfile.GetProfile(args.AnonymousID);
        var f = UserProfile.GetProfile(); // current logged in user profile

        if (anonymousProfile.LastVisit.HasValue)
        {
            f.LastVisit = anonymousProfile.LastVisit;
            f.Save();
        }

        ProfileManager.DeleteProfile(args.AnonymousID);
        AnonymousIdentificationModule.ClearAnonymousIdentifier();
        Membership.DeleteUser(args.AnonymousID, true);
    }
.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top