我可以在MVC控制器中使用Profile的动态功能吗?

时间:2013-09-05 12:56:45

标签: c# asp.net-mvc-4

我怀疑这只适用于asp.net页面,但根据这个:

http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx

我可以在web.config中定义属性,如下所示:

<profile>
  <properties>
    <add name="PostalCode" />
  </properties>
</profile>

然后继续使用它们:

Profile.PostalCode = txtPostalCode.Text;

但是这不能在Controller中为我编译:

public ActionResult Index()
{
  Profile.PostalCode = "codeofpost";
  return View();
}

Profile属于ProfileBase类型且不是动态的,所以我不知道这是如何工作的,但文档说不然。

2 个答案:

答案 0 :(得分:1)

Profile类仅在ASP.NET网站项目中生成,而不是在ASP.NET Web应用程序中生成。

在Web应用程序项目中,您需要使用

ProfielBase.GetPropertyValue(PropertyName);

参考文献:http://weblogs.asp.net/anasghanem/archive/2008/04/12/the-differences-in-profile-between-web-application-projects-wap-and-website.aspx

答案 1 :(得分:0)

因为我被告知这是不可能的,所以我决定用动态为自己做这件事。我想这最终只是语法糖。

从此降序可启用Profile.PostalCode = "codeofpost";

/// <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; }
    }
}