【问题标题】:Use a Profile in an ASP.NET Web Application [duplicate]在 ASP.NET Web 应用程序中使用配置文件 [重复]
【发布时间】:2011-07-23 22:45:37
【问题描述】:

可能重复:
How to assign Profile values?

我正在阅读一本 ASP.NET 书籍,它说如果在启动项目时选择 Web 应用程序,则不能使用 Profile。它只在网站下运行。

Web 应用程序有替代方案吗?或者您是否需要建立自己的个人资料系统。

【问题讨论】:

标签: asp.net


【解决方案1】:

如果您使用的是 Web 应用程序而不是网站,则可以使用配置文件提供程序,但您后面的 aspx 页面代码的开箱即用将无法执行 Profile.MyProperty

这没什么大不了的,只要稍加努力,您就可以做类似的事情。 Converting a Web Site Project to a Web Application Project 中提供的示例是关于如何将配置文件提供程序与 Web 应用程序一起使用的一个很好的起点。

总结上述文章的转换配置文件对象代码部分,创建一个ProfileCommon

public class ProfileCommon
{
    public Teachers Teachers
    {
        get
        {
            return (Teachers)
                HttpContext.Current.Profile.GetPropertyValue("Teachers");
        }
        set
        {
            HttpContext.Current.Profile.SetPropertyValue("Teachers",value);
        }
    }
}

然后在你的aspx代码后面你现在可以做

ProfileCommon Profile = new ProfileCommon();
protected void Button1_Click(object sender, EventArgs e)
{
    Teachers teachers = new Teachers();
    teachers.Add(new Teacher("scott"));
    teachers.Add(new Teacher("bob"));
    teachers.Add(new Teacher("paul"));

    Profile.Teachers = teachers;    
}

ProfileCommon 实例化为每个页面的字段的另一种方法是将其及其方法设为静态,然后从Profile.Teachers 后面的代码中调用类属性

public static class Profile
{
    public static Teachers Teachers
    {
        //......
    }
}

这不是一个巨大的优势,但会使您的代码更类似于 ASP.NET 网站项目的代码。

与答案无关的社论评论
两种项目类型之间存在关键差异,但对于我的项目,我更喜欢 Web 应用程序。我有一个偏见,因为为 Web 应用程序项目创建 TFS 构建管理器的构建配置文件比为网站项目更容易。此外,微软似乎强调了网站项目,然后又放弃了这些项目,转而支持 Web 应用程序项目。

【讨论】:

  • 你可能希望ProfileCommon继承自ProfileBase,如:public class ProfileCommon : ProfileBase
猜你喜欢
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 2015-08-28
  • 2013-03-23
  • 2020-09-20
  • 2012-06-02
相关资源
最近更新 更多