如何在ASP.NET 4.5中访问web.config配置文件属性?

时间:2014-01-28 15:23:27

标签: c# asp.net .net

我浏览ASP.NET 4.0在线资源,这只是最初的课程之一。

我安装了Visual Studio 2012 for Web,并且它已安装了ASP.NET 4.5。

为了访问某些web.config属性,课程中的人写下以下行:

Profile.Preferences.MyParameter = "MyValue";

但是当我输入相同的内容时,它会给我一个错误: Profile element doesn't exist in the current context 。当我尝试访问System.Web.Profile.Preferences时,它会说 Type or namespace "Preferences" is missing in System.Web.Profile

任何人都可以告诉我们发生了什么事吗? ASP.NET 4.5是否是这种行为的原因,如果是 - 我如何访问相同的web.config属性是ASP.NET 4.5?

我的web.config看起来像这样:

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <profile>
      <properties>
        <group name="Preferences">
          <add name="MyParameter"/>
        </group>
      </properties>
    </profile>
  </system.web>
</configuration>

更新: 我试图从Joel Spolsky的答案中实现第二个解决方案:How to assign Profile values?

但代码对我不起作用。以下方法是:

static public AccountProfile CurrentUser
    {
        get { return (AccountProfile)
                     (ProfileBase.Create(Membership.GetUser().UserName)); }
    }

发生这种情况是因为Membership.GetUser()返回null。我该怎么办?

1 个答案:

答案 0 :(得分:0)

根据您的描述,我认为问题在于它不正确地引用,因此找不到您要访问的内容。

我猜你试过了: How to assign Profile values?

当你引用作者时,Joel Spolskys答案的第一部分是你使用的应用程序类型??? Visual Studio中有两种项目 - “Web站点项目”和“Web应用程序项目”。 还有其他几种类型的项目,但这些是主要的“网络”应用程序。

如何访问属性的确切细节因框架和应用程序类型而异。例如,如果您在Windows窗体中拥有app.config,或者如果您在Web应用程序中拥有web.config。您是否制作了web.config或者它已经编辑了吗?

我可以尝试解释如何访问属性,但如果它与应用程序的类型不同,则无论如何都无法工作。

您可以先查看一下吗? determine project type in visual studio

如果您在错误的项目类型中尝试以正确的类型创建一个新项目,那么查看您现有的代码是否正常工作。

相关问题