C# 我可以在MVC控制器中使用Profile的动态功能吗?
我怀疑这只适用于asp.net页面,但根据这一点: 我可以在C# 我可以在MVC控制器中使用Profile的动态功能吗?,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我怀疑这只适用于asp.net页面,但根据这一点: 我可以在web.config中定义属性,如下所示: <profile> <properties> <add name="PostalCode" /> </properties> </profile> 但在控制器中,这不会为我编译: public ActionResult Index() { Profile.PostalCode = "codeofpost";
web.config
中定义属性,如下所示:
<profile>
<properties>
<add name="PostalCode" />
</properties>
</profile>
但在控制器中,这不会为我编译:
public ActionResult Index()
{
Profile.PostalCode = "codeofpost";
return View();
}
Profile
属于ProfileBase
类型,并且不是动态的,因此我不知道这将如何工作,但文档中另有说明。Profile类仅在ASP.NET网站项目中生成,而不是在ASP.NET Web应用程序中生成
在Web应用程序项目中,您需要使用
ProfielBase.GetPropertyValue(PropertyName);
参考资料:有人告诉我这是不可能的,我决定用一个动态来为自己做这件事。我猜最后只是语法上的甜点 从此处开始递减将启用
Profile.PostalCode=“codeofpost”代码>
//
///提供动态配置文件。
///
公共抽象类ControllerBase:Controller
{
私有只读惰性配置文件;
受保护控制器数据库()
{
_dProfile=newlazy(()=>newdynamicprofile(base.Profile));
}
私有密封类DynamicProfile:DynamicObject
{
私有只读配置文件库\u配置文件;
公共动态配置文件(ProfileBase配置文件)
{
_外形=外形;
}
公共重写bool TryGetMember(GetMemberBinder绑定器,输出对象结果)
{
结果=_profile.GetPropertyValue(binder.Name);
返回true;
}
public override bool TrySetMember(SetMemberBinder绑定器,对象值)
{
_profile.SetPropertyValue(binder.Name,value);
_profile.Save();
返回true;
}
}
///
///新的动态配置文件,现在可以像在配置文件上一样访问属性,
///例如,个人资料、邮政编码
///
受保护的新动态配置文件
{
获取{return}dProfile.Value;}
}
///
///提供对原始配置文件对象的访问。
///
受保护的ProfileBase ProfileBase
{
获取{return base.Profile;}
}
}
你在web.config中定义了这个属性吗?@KirillBestemyanov-yesOh我明白了,谢谢,我找到了一种方法,但是它并没有像网站项目那样让你完成代码。你为什么不创建自定义类MyProfile:ProfileBase,在Get中使用ProfielBase.GetPropertyValue的属性。哦,是的,那会更好!
ProfielBase.GetPropertyValue(PropertyName);
/// <summary>
/// Provides a dynamic Profile.
/// </summary>
public abstract class ControllerBase : Controller
{
private readonly Lazy<DynamicProfile> _dProfile;
protected ControllerBase()
{
_dProfile = new Lazy<DynamicProfile>(() => new DynamicProfile(base.Profile));
}
private sealed class DynamicProfile : DynamicObject
{
private readonly ProfileBase _profile;
public DynamicProfile(ProfileBase profile)
{
_profile = profile;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = _profile.GetPropertyValue(binder.Name);
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_profile.SetPropertyValue(binder.Name, value);
_profile.Save();
return true;
}
}
/// <summary>
/// New dynamic profile, can now access the properties as though they are on the Profile,
/// e.g. Profile.PostCode
/// </summary>
protected new dynamic Profile
{
get { return _dProfile.Value; }
}
/// <summary>
/// Provides access to the original profile object.
/// </summary>
protected ProfileBase ProfileBase
{
get { return base.Profile; }
}
}