代码之家  ›  专栏  ›  技术社区  ›  Pablo Fernandez

如何在ASP.NET MVC的视图中填充profile变量?

  •  0
  • Pablo Fernandez  · 技术社区  · 15 年前

    在ASP.NET MVC的视图中,我可以这样访问配置文件和配置文件成员:

    <%= Profile.Name %> - <%= Profile.Karma %>
    

    但是如何填充配置文件变量呢?它似乎在httpcontext.current.profile中。我用currentUser方法编写了一个自定义配置文件类,如下所示:

    static public Profile CurrentUser {
        get {
            return (Profile) (ProfileBase.Create(Membership.GetUser().UserName));
        }
    }
    

    我的web.config中提到了这个类:

    <profile inherits="MyProject.Models.Profile" defaultProvider="AspNetSqlProfileProvider" enabled="true">
        <providers>
            <clear />
            <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
        </providers>
    </profile>
    

    这是:

    var p = CurrentUser.Profile
    

    成功地为我提供了配置文件,但我不能这样设置:

    HttpContext.Profile = CurrentUser.Profile;
    

    因为httpContext.profile是只读的。我得到错误:

    错误18属性或索引器“system.web.httpContextBase.profile”无法分配给--它是只读的C:…\controller.cs 26 17 myproject

    另外,我需要为每个视图分配配置文件,这样登录用户的名称就可以以通常的方式显示在右上角。我该怎么做?

    3 回复  |  直到 15 年前
        1
  •  0
  •   Dan Diplo    15 年前

    假设您已经在web.config中设置了默认的配置文件提供程序。

    <profile defaultProvider="MyCustomProfileProvider">
      <properties>
        <!-- etc. -->
      </properties>
    </profile>
    

    不确定MVC,但需要标准ASP.NET。

        2
  •  0
  •   Pablo Fernandez    15 年前

    之所以得到一个空名称,并不是因为我没有得到配置文件,而是因为数据库中的配置文件实际上是空的(因为我的代码中有一个不相关的bug)。我所说的一切都是为了让档案工作。

        3
  •  -1
  •   J.W.    15 年前

    我需要分配的配置文件 每个视图的名称 登录用户可以显示在 按常规方式右上角

    您可以创建一个登录控件,并在该控件中编写此控件。

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <%
        if (Request.IsAuthenticated) {
    %>
            Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
            [ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ]
    <%
        }
        else {
    %> 
            [ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ]
    <%
        }
    %>
    

    httpContext对象也具有用户属性。