我正在使用MVC4,我想在配置文件中存储几个值。
为什么
TempData["badgerName"] = Profile.BadgerName;
说ProfileBase不包含BadgerName的定义吗?
我已将配置文件设置如下。
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add
name="DefaultProfileProvider"
type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="FALContext"
applicationName="/" />
</providers>
<properties>
<add name="BadgerName" type="String"/>
</properties>
</profile>
答案 0 :(得分:1)
在ASP MVC中,您没有为您的站点生成使用web.config文件中定义的属性的配置文件对象。可以从控制器方法访问的属性Profile
的类型为ProfileBase
(see msdn),并且不包含自定义配置文件属性的强类型属性。您可能也知道,在请求开始时为登录用户加载此配置文件,并在请求结束时保存所有更改。
有different ways您可以使用ProfileBase
课程。最常用的是:
直接使用ProfileBase
时,您需要使用控制器方法中的实例或获取给定用户名的实例。然后,您应该使用索引器来访问配置文件属性。假设您的控制器方法收到UserModel类型的对象,其中包含您的用户数据,如电子邮件和BadgerName,那么您可以编写如下代码:
//Getting the instance from the controller property:
ProfileBase profile = this.Profile; //or even: this.HttpContext.Profile
//You can also get the profile for a given existing user.
ProfileBase profile = ProfileBase.Create(userModel.Name);
//Then update properties using indexer
profile["Email"] = userModel.Email;
profile["BadgerName"] = userModel.BadgerName;
//Manually save changes
//(Can be skipped for the profile automatically loaded in the Controller)
profile.Save();
但是,如果您从ProfileBase
创建派生类,您将最终以与原定预期相同的方式使用您的类。您基本上将创建一个包含强类型属性的包装类,使用索引器在内部访问ProfileBase(方法摘要为here):
public class MyCustomProfile : ProfileBase
{
public string Email
{
get { return base["Email"] as string; }
set { base["Email"] = value; }
}
public string BadgerName
{
get { return base["BadgerName"] as string; }
set { base["BadgerName"] = value; }
}
//If needed, you can provide methods to recover profiles
//for the logged in user or any user given its user name
public static MyCustomProfile GetCurrent()
{
return Create(Membership.GetUser().UserName) as MyCustomProfile;
}
public static MyCustomProfile GetProfile(string userName)
{
return Create(userName) as MyCustomProfile;
}
}
如果使用此选项,还需要确保web.config的<profile>
元素的inherits
属性设置为自定义模型类:
<profile enabled="true" defaultProvider="DefaultProfileProvider" inherits="yourNamespace.MyCustomProfile">
使用此代码和配置,您可以通过恢复用户配置文件或将控制器配置文件属性强制转换为自定义类来开始使用自定义配置文件类:
//Cast the Profile property of the controller to your custom class
MyCustomProfile profile = this.Profile as MyCustomProfile // or even: HttpContext.Profile as MyCustomProfile
//You could also manually load the profile for given an user name
profile = MyCustomProfile.GetProfile(userModel.Name);
//Or even manually load the profile for the logged in user
profile = MyCustomProfile.GetCurrent();
//Now get/set the profile properties using the strongly typed properties of your class
profile.Email= userModel.Email;
profile.BadgerName= userModel.BadgerName;
//Manually save changes
//(Can be skipped for the profile automatically loaded in the Controller)
profile.Save();
希望这有帮助!