在ASP.NET Web应用程序中使用配置文件

Tea*_*eek 5 asp.net

可能重复:
如何分配配置文件值?

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

Web应用程序有其他替代方案吗?或者您是否需要构建自己的Profile系统.

ahs*_*ele 8

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

这不是什么大问题,因为只需要一点努力就可以做类似的事情.将Web站点项目转换为Web应用程序项目提供的示例是如何将概要文件提供程序与Web应用程序一起使用的一个很好的起点.

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

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

然后在你的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;    
}
Run Code Online (Sandbox Code Playgroud)

ProfileCommon为每个页面实例化一个字段的另一种方法是使它和它的方法静态,只需从代码后面调用类属性Profile.Teachers

public static class Profile
{
    public static Teachers Teachers
    {
        //......
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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