如何分配Profile值?

发布于 2024-10-24 15:55:10 字数 92 浏览 5 评论 0原文

我不知道我缺少什么,但我在 Web.config 文件中添加了 Profile 属性,但无法访问代码中的 Profile.Item 或创建新的配置文件。

I don't know what I am missing, but I added Profile properties in the Web.config file but cannot access Profile.Item in the code or create a new profile.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

忆悲凉 2024-10-31 15:55:10

我今天也遇到了同样的问题,学到了很多东西。

Visual Studio 中有两种项目——“网站项目”和“Web 应用程序项目”。由于对我来说完全是个谜的原因,Web 应用程序项目无法直接使用 Profile....强类型类不会从 Web.config 文件中神奇地为您生成,因此您必须自己动手。

MSDN 中的示例代码假设您正在使用网站项目,并且它们告诉您只需将 部分添加到您的 Web.config 中,然后继续使用配置文件。属性,但这在 Web 应用程序项目中不起作用。

您有两种选择来自行构建:

(1) 使用Web 配置文件生成器。这是添加到 Visual Studio 的自定义工具,它会根据 Web.config 中的定义自动生成所需的 Profile 对象。

我选择不这样做,因为我不希望我的代码依赖于这个额外的工具来编译,这可能会给其他人带来问题,当他们尝试构建我的代码时却没有意识到他们需要这个工具。

(2) 创建您自己的从 ProfileBase 派生的类来表示您的自定义配置文件。这比看起来容易。这是一个非常非常简单的示例,添加了“FullName”字符串配置文件字段:

在您的 web.config 中:

<profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile">

<providers>
     <clear />
     <add name="SqlProvider"
          type="System.Web.Profile.SqlProfileProvider"
          connectionStringName="sqlServerMembership" />
</providers>

</profile>

在名为 AccountProfile.cs 的文件中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

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

        public string FullName
        {
            get { return ((string)(base["FullName"])); }
            set { base["FullName"] = value; Save(); }
        }

        // add additional properties here
    }
}

设置配置文件值:

AccountProfile.CurrentUser.FullName = "Snoopy";

获取配置文件值

string x = AccountProfile.CurrentUser.FullName;

I had the same problem today, and learned a lot.

There are two kinds of project in Visual Studio -- "Web Site Projects" and "Web Application Projects." For reasons which are a complete mystery to me, Web Application Projects cannot use Profile. directly... the strongly-typed class is not magically generated for you from the Web.config file, so you have to roll your own.

The sample code in MSDN assumes you are using a Web Site Project, and they tell you just to add a <profile> section to your Web.config and party on with Profile.property, but that doesn't work in Web Application Projects.

You have two choices to roll your own:

(1) Use the Web Profile Builder. This is a custom tool you add to Visual Studio which automatically generates the Profile object you need from your definition in Web.config.

I chose not to do this, because I didn't want my code to depend on this extra tool to compile, which could have caused problems for someone else down the line when they tried to build my code without realizing that they needed this tool.

(2) Make your own class that derives from ProfileBase to represent your custom profile. This is easier than it seems. Here's a very very simple example that adds a "FullName" string profile field:

In your web.config:

<profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile">

<providers>
     <clear />
     <add name="SqlProvider"
          type="System.Web.Profile.SqlProfileProvider"
          connectionStringName="sqlServerMembership" />
</providers>

</profile>

In a file called AccountProfile.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

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

        public string FullName
        {
            get { return ((string)(base["FullName"])); }
            set { base["FullName"] = value; Save(); }
        }

        // add additional properties here
    }
}

To set a profile value:

AccountProfile.CurrentUser.FullName = "Snoopy";

To get a profile value

string x = AccountProfile.CurrentUser.FullName;
小…红帽 2024-10-31 15:55:10

Web 应用程序项目仍然可以使用 ProfileCommon 对象,但只能在运行时使用。它的代码不是在项目本身中生成的,而是由 ASP.Net 生成的类并在运行时存在。

获取对象的最简单方法是使用动态类型,如下所示。

在 Web.config 文件中声明配置文件属性:

<profile ...
 <properties>
   <add name="GivenName"/>
   <add name="Surname"/>
 </properties>

然后访问属性:

dynamic profile = ProfileBase.Create(Membership.GetUser().UserName);
string s = profile.GivenName;
profile.Surname = "Smith";

保存对配置文件属性的更改:

profile.Save();

如果您习惯使用动态类型并且不介意缺少编译时检查和智能感知,则上述方法可以正常工作。

如果将其与 ASP.Net MVC 一起使用,则在将动态配置文件对象传递到视图时必须做一些额外的工作,因为 HTML 帮助器方法不能很好地处理动态的“模型”对象。在将配置文件属性传递给 HTML 帮助器方法之前,您必须将它们分配给静态类型变量。

// model is of type dynamic and was passed in from the controller
@Html.TextBox("Surname", model.Surname) <-- this breaks

@{ string sn = model.Surname; }
@Html.TextBox("Surname", sn); <-- will work

如果您创建自定义配置文件类,如 Joel 上面所述,ASP.Net 仍将生成 ProfileCommon 类,但它将继承自您的自定义配置文件类。如果不指定自定义配置文件类,ProfileCommon 将从 System.Web.Profile.ProfileBase 继承。

如果您创建自己的配置文件类,请确保您没有在已在自定义配置文件类中声明的 Web.config 文件中指定配置文件属性。如果这样做,ASP.Net 在尝试生成 ProfileCommon 类时将给出编译器错误。

Web Application Projects can still use the ProfileCommon object but only at runtime. The code for it is just not generated in the project itself but the class is generated by ASP.Net and is present at runtime.

The simplest way to get to object is to use a dynamic type as demonstrated below.

In the Web.config file declare the profile properties:

<profile ...
 <properties>
   <add name="GivenName"/>
   <add name="Surname"/>
 </properties>

Then to access the properties:

dynamic profile = ProfileBase.Create(Membership.GetUser().UserName);
string s = profile.GivenName;
profile.Surname = "Smith";

To save changes to profile properties:

profile.Save();

The above works fine if you are comfortable using dynamic types and don't mind the lack of compile-time checking and intellisense.

If you use this with ASP.Net MVC you have to do some additional work if you pass the dynamic profile object to your views since the HTML helper methods don't play well with "model" objects that are dynamic. You will have to assign profile properties to statically typed variables before passing them to HTML helper methods.

// model is of type dynamic and was passed in from the controller
@Html.TextBox("Surname", model.Surname) <-- this breaks

@{ string sn = model.Surname; }
@Html.TextBox("Surname", sn); <-- will work

If you create a custom profile class, as Joel described above, ASP.Net will still generate the ProfileCommon class but it will inherit from your custom profile class. If you don't specify a custom profile class ProfileCommon will inherit from System.Web.Profile.ProfileBase.

If you create your own profile class make sure that you don't specify profile properties in the Web.config file that you've already declared in your custom profile class. If you do ASP.Net will give a compiler error when it tries to generate the ProfileCommon class.

往日情怀 2024-10-31 15:55:10

Profile 也可以在 Web 应用程序项目中使用。
这些属性可以在设计时或以编程方式在 Web.config 中定义。在 Web.config 中:

<profile enabled="true" automaticSaveEnabled="true" defaultProvider="AspNetSqlProfileProvider">
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="TestRolesNProfiles"/>
      </providers>
      <properties>
        <add name="FirstName"/>
        <add name="LastName"/>
        <add name ="Street"/>
        <add name="Address2"/>
        <add name="City"/>
        <add name="ZIP"/>
        <add name="HomePhone"/>
        <add name="MobilePhone"/>
        <add name="DOB"/>

      </properties>
    </profile>

或以编程方式,通过实例化 ProfileSection 并使用 ProfilePropertySettingsProfilePropertySettingsCollection 创建单独的属性来创建配置文件部分,所有这些属性都是在 System.Web.Configuration 命名空间中。
要使用配置文件的这些属性,请使用 System.Web.Profile.ProfileBase 对象。如上所述,配置文件属性无法使用 profile. 语法进行访问,但可以通过实例化 ProfileBase 并使用 SetPropertyValue("PropertyName ") 和 GetPropertyValue{"PropertyName") 如下:

ProfileBase curProfile = ProfileBase.Create("MyName");

或访问当前用户的个人资料:

ProfileBase curProfile = ProfileBase.Create(System.Web.Security.Membership.GetUser().UserName);



        curProfile.SetPropertyValue("FirstName", this.txtName.Text);
        curProfile.SetPropertyValue("LastName", this.txtLname.Text);
        curProfile.SetPropertyValue("Street", this.txtStreet.Text);
        curProfile.SetPropertyValue("Address2", this.txtAdd2.Text);
        curProfile.SetPropertyValue("ZIP", this.txtZip.Text);
        curProfile.SetPropertyValue("MobilePhone", txtMphone.Text);
        curProfile.SetPropertyValue("HomePhone", txtHphone.Text);
        curProfile.SetPropertyValue("DOB", txtDob.Text);
        curProfile.Save();

Profile can be used in Web Application Projects too.
The properties can be defined in Web.config at design time or programmatically. In Web.config:

<profile enabled="true" automaticSaveEnabled="true" defaultProvider="AspNetSqlProfileProvider">
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="TestRolesNProfiles"/>
      </providers>
      <properties>
        <add name="FirstName"/>
        <add name="LastName"/>
        <add name ="Street"/>
        <add name="Address2"/>
        <add name="City"/>
        <add name="ZIP"/>
        <add name="HomePhone"/>
        <add name="MobilePhone"/>
        <add name="DOB"/>

      </properties>
    </profile>

or Programmatically, create the profile section by instantiating a ProfileSection and creating individual properties using ProfilePropertySettings and ProfilePropertySettingsColletion, all of which are in System.Web.Configuration Namespace.
To use those properties of the profile, use System.Web.Profile.ProfileBase Objects. The profile properties cannot be accessed with profile. syntax as mentioned above, but can be easily done by instantiating a ProfileBase and using SetPropertyValue("PropertyName") and GetPropertyValue{"PropertyName") as follows:

ProfileBase curProfile = ProfileBase.Create("MyName");

or to access the profile of current user:

ProfileBase curProfile = ProfileBase.Create(System.Web.Security.Membership.GetUser().UserName);



        curProfile.SetPropertyValue("FirstName", this.txtName.Text);
        curProfile.SetPropertyValue("LastName", this.txtLname.Text);
        curProfile.SetPropertyValue("Street", this.txtStreet.Text);
        curProfile.SetPropertyValue("Address2", this.txtAdd2.Text);
        curProfile.SetPropertyValue("ZIP", this.txtZip.Text);
        curProfile.SetPropertyValue("MobilePhone", txtMphone.Text);
        curProfile.SetPropertyValue("HomePhone", txtHphone.Text);
        curProfile.SetPropertyValue("DOB", txtDob.Text);
        curProfile.Save();
沐歌 2024-10-31 15:55:10

当您在 Visual Studio 中创建新的网站项目时,将从配置文件返回的对象将(自动)为您生成。当您创建 Web 应用程序项目或 MVC 项目时,您必须推出自己的项目。

这听起来可能比实际上更困难。您需要执行以下操作:

  • 使用 aspnet_regsql.exe 创建数据库 该工具与 .NET 框架一起安装。
  • 编写一个从 ProfileGroupBase 派生的类,或者安装 Web Profile Builder (WPB),它可以根据 Web.Config 中的定义为您生成该类。我已经使用 WPB 一段时间了,到目前为止它已经达到了预期的效果。如果您有很多属性,使用 WPB 可以节省大量时间。
  • 确保在 Web.Config 中正确配置了与数据库的连接。
  • 现在您准备创建配置文件类的实例(在控制器中),
  • 您可能需要在视图中配置配置文件属性值。我喜欢将配置文件对象本身传递给视图(而不是单个属性)。

When you create a new Web site project in Visual Studio then the object that is returned from Profile will be (automatically) generated for you. When you create a Web application project or an MVC project, you will have to roll your own.

This probably sounds more difficult than it is. You need to do the following:

  • Create a database using aspnet_regsql.exe This tool is installed along with the .NET framework.
  • Write a class that derives from ProfileGroupBase or install the Web Profile Builder (WPB) that can generate the class for you from the definition in Web.Config. I have been using WPB for a while and up until now it has done what is expected of it. If you have a lot of properties, using WPB can save quite a bit of time.
  • Make sure the connection to the database is properly configured in Web.Config.
  • Now you are set to create an instance of your profile class (in the controller)
  • You will probably need the profile property values in your views. I like to pass the profile object itself along to the view (not individual properties).
甜宝宝 2024-10-31 15:55:10

如果您使用的是 Web 应用程序项目,则无法在设计时直接访问 Profile 对象。这是一个据称可以为您完成此操作的实用程序:http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx。就我个人而言,该实用程序在我的项目中导致了错误,因此我最终滚动了自己的配置文件类以从 ProfileBase 继承。这并不难做到。

If you are using a web application project, you cannot access the Profile object at design-time out-of-the-box. Here is a utility that supposedly does it for you: http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx. Personally, that utility caused an error in my project so I ended up rolling my own profile class to inherit from ProfileBase. It was not hard to do at all.

仅此而已 2024-10-31 15:55:10

创建自定义类(又名 Joel 方法)的 MSDN 演练:
http://msdn.microsoft.com/en-us/magazine/cc163624。 ASPX

MSDN walkthrough for creating a custom class (a.k.a. Joel's method):
http://msdn.microsoft.com/en-us/magazine/cc163624.aspx

简单气质女生网名 2024-10-31 15:55:10

我也遇到了同样的问题。但我没有创建一个继承自 ProfileBase 的类,而是使用了 HttpContext。

在 web.config 文件中指定属性,如下所示:-
ProfilePropertyWeb.config

现在,编写以下代码: -

Code Behind Profile Properties

编译并运行代码。您将得到以下输出: -

Output

I was also running through the same issue. But instead of creating a class which inherits from ProfileBase, I used the HttpContext.

Specify properties in web.config file as follows : -
ProfilePropertyWeb.config

Now, write the following code : -

Code Behind Profile Properties

Compile and run the code. You will get following output: -

Output

风渺 2024-10-31 15:55:10

Web 配置文件生成器 对我来说非常有用。它生成的类比 Joel 的帖子中描述的要多得多。我不知道它是否真的需要或有用。

无论如何,对于那些寻找一种简单方法来生成类,但又不想有外部构建工具依赖项的人,您可以随时

  • 使用 Web 配置文件生成器
  • 删除它的所有痕迹!
  • 继续使用生成的 Profile 类

或(未经测试但可能有效)

  • 创建一个 Web site 项目
  • 创建您的元素
  • 捕捉生成的类并将其复制到您的 Web project 项目,

如果第二种方法确实有效,有人可以告诉我以供将来参考吗

The Web Profile Builder worked great for me. The class it generated has a lot more in it than as described by Joel's post. Whether or not its actually needed or useful I dont know.

Anyway for those looking for an easy way to generate the class, but not wanting to have an external build tool dependency you can always

  • use the web profile builder
  • delete all trace of it!
  • keep using the generated Profile class

OR (untested but may just work)

  • create a web site project
  • create your element
  • snap the generated class and copy it over to your web project project

if this second approach does work can someone let me know for future reference

左耳近心 2024-10-31 15:55:10

只是想补充 Joel Spolsky 的答案,

我实现了他的解决方案,顺便说一句,工作非常出色 - Cudos!

对于任何想要获取不是我使用的登录用户的用户配置文件的人:

web.config:

  <connectionStrings>
    <clear />
    <add name="LocalSqlConnection" connectionString="Data Source=***;Database=***;User Id=***;Password=***;Initial Catalog=***;Integrated Security=false" providerName="System.Data.SqlClient" />
  </connectionStrings>

然后

<profile defaultProvider="SqlProvider" inherits="NameSpace.AccountProfile" enabled="true">
  <providers>
    <clear/>
    <add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LocalSqlConnection"/>
  </providers>

是我的自定义类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

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

        static public AccountProfile GetUser(MembershipUser User)
        {
            return (AccountProfile)
                (ProfileBase.Create(User.UserName));
        }

        /// <summary>
        /// Find user with matching barcode, if no user is found function throws exception
        /// </summary>
        /// <param name="Barcode">The barcode to compare against the user barcode</param>
        /// <returns>The AccountProfile class with matching barcode or null if the user is not found</returns>
        static public AccountProfile GetUser(string Barcode)
        {
            MembershipUserCollection muc = Membership.GetAllUsers();

            foreach (MembershipUser user in muc)
            {
                if (AccountProfile.GetUser(user).Barcode == Barcode)
                {
                    return (AccountProfile)
                        (ProfileBase.Create(user.UserName));
                }
            }
            throw new Exception("User does not exist");
        }

        public bool isOnJob
        {
            get { return (bool)(base["isOnJob"]); }
            set { base["isOnJob"] = value; Save(); }
        }

        public string Barcode
        {
            get { return (string)(base["Barcode"]); }
            set { base["Barcode"] = value; Save(); }
        }
    }
}

就像魅力一样...

Just want to add to Joel Spolsky's answer

I implemented his solution, working brilliantly btw - Cudos!

For anyone wanting to get a user profile that's not the logged in user I used:

web.config:

  <connectionStrings>
    <clear />
    <add name="LocalSqlConnection" connectionString="Data Source=***;Database=***;User Id=***;Password=***;Initial Catalog=***;Integrated Security=false" providerName="System.Data.SqlClient" />
  </connectionStrings>

and

<profile defaultProvider="SqlProvider" inherits="NameSpace.AccountProfile" enabled="true">
  <providers>
    <clear/>
    <add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LocalSqlConnection"/>
  </providers>

And then my custom class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

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

        static public AccountProfile GetUser(MembershipUser User)
        {
            return (AccountProfile)
                (ProfileBase.Create(User.UserName));
        }

        /// <summary>
        /// Find user with matching barcode, if no user is found function throws exception
        /// </summary>
        /// <param name="Barcode">The barcode to compare against the user barcode</param>
        /// <returns>The AccountProfile class with matching barcode or null if the user is not found</returns>
        static public AccountProfile GetUser(string Barcode)
        {
            MembershipUserCollection muc = Membership.GetAllUsers();

            foreach (MembershipUser user in muc)
            {
                if (AccountProfile.GetUser(user).Barcode == Barcode)
                {
                    return (AccountProfile)
                        (ProfileBase.Create(user.UserName));
                }
            }
            throw new Exception("User does not exist");
        }

        public bool isOnJob
        {
            get { return (bool)(base["isOnJob"]); }
            set { base["isOnJob"] = value; Save(); }
        }

        public string Barcode
        {
            get { return (string)(base["Barcode"]); }
            set { base["Barcode"] = value; Save(); }
        }
    }
}

Works like a charm...

反差帅 2024-10-31 15:55:10

很棒的帖子,

只是 web.config 上的一个注释
如果您没有在 profile 元素中指定继承属性
您需要在配置文件中指定每个单独的配置文件属性
web.config 中的元素如下

 <properties>
    <clear/>
    <add name="property-name-1" />
    <add name="property-name-2" />
    ..........

 </properties>

Great post,

Just a note on the web.config
if you dont specify the inherit attribute in the profile element
you will need to specify each indiviudal profile property inside the profile
element on the web.config as below

 <properties>
    <clear/>
    <add name="property-name-1" />
    <add name="property-name-2" />
    ..........

 </properties>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文