如何在Web App Project 或者 Web Site Project的App_Code 内使用 Profile/ProfileCommon

在 web site project 内 可以很方便的使用 Profile/ProfileCommon 来 访问我们在web.config 的profile节内定义的properties , 并且有很爽的 intellisense
然而在Web App Project或者Web Site Project的App_Code内使用的时候 编译都通不过的,因为 Profile 是 web site project 模型 在页面 执行时候创建在HttpContext的,Web Site Project 或者App_Code编译的时候还没有页面实例呢,何谈HttpContext, 当然无法使用了

引用scottgu的原话解释“This is supported because with the VS 2005 Web Site Project option Visual Studio is dynamically creating and adding a "ProfileCommon" class named "Profile" into every code-behind instance”,那么怎么办呢 scottgu 支招------“VS 2005 Web Application Projects don't automatically support generating a strongly-typed Profile class proxy. However, you can use this free download to automatically keep your own proxy class in sync with the profile configuration”。

我们可以到 gotdotnet 上下载这个 addin  安装,经我测试 这个东西装在中文VS2005 SP1 上右键不会出现菜单(只会出现在外部程序管理器内,看的到用不成,不开心)。
好在他有源码的,我们用他的源码 找到 大概 40行上下
string toolsMenuName ;定义部分
直接 string toolsMenuName = "工具"; 然后下面的 try catch 注释掉----编译---然后把dll文件
替换到 C:\Documents and Settings\武眉博\My Documents\Visual Studio 2005\AddIns
就可以用了(原因可能是他的资源文件有问题)
接下来按照readme使用吧。
==================================================
To use the generator right click on web.config in a Web Application Project and
select "Generate WebProfile."  This will create a WebProfile class in your
project based on the current profile setting sin Web.Config.  If you make a
change to your profile setting you need to run the tool again to update the
WebProfile class.  The WebProfile class is simply a thin wrapper that has
strongly typed accessors to profile properties.

To use the web profile class in a page create an accessor like this:

    // C# accessor
    private WebProfile Profile
    {
        get { return new WebProfile(Context.Profile); }
    }

    ' VB accessor
    Private ReadOnly Property Profile() As WebProfile
        Get
            Return New WebProfile(Context.Profile)
        End Get
    End Property

Then you can use it like this:

    // C# use or accessor
    string s = Profile.MyProperty;
    Profile.MyGroup.MyProperty = "value";

    ' VB use of accessor
    Dim prop As String = Profile.MyProperty
    Profile.MyGroup.MyProperty = "value"

You can also access the current profile using the static Current property
like this:

    // C# use of Current property
    string s = WebProfile.Current.MyProperty;
    WebProfile.Current.MyGroup.MyProperty = "value";

    // VB use of Current property
    Dim s As String = WebProfile.Current.MyProperty
    WebProfile.Current.MyGroup.MyProperty = "value"
    ========================================================
如果你用的是Web Site Project 想在App_Code内用Profile那么建议 创建一个WebSiteProject web.config拷贝过去仍然使用这个AddIn生成一个WebProfile.cs拷贝回你的app_code内就可以了(哎,怎么感觉像是说了个废话,还不如直接用Web App Project呢)
OK,就这么几步了。记在这里希望对朋友们有用,睡觉了。

参考资料: http://webproject.scottgu.com/CSharp/migration2/migration2.aspx

posted on 2007-06-06 22:52  活靶子.Net  阅读(4041)  评论(3编辑  收藏  举报

导航