【问题标题】:HTTPContext.Current.User.Identity.Name not working inside a control?HTTPContext.Current.User.Identity.Name 在控件中不起作用?
【发布时间】:2012-03-20 12:28:02
【问题描述】:

我有一个标签,我想将此标签的文本设置为

HTTPContext.Current.User.Identity.Name

所以我写了

Text = '<%=HTTPContext.Current.User.Identity.Name %>'

但它不起作用,但是当我在标签之外写这个时,例如:

<h2>
<%=HTTPContext.Current.User.Identity.Name %>
</h2>

它有效。

【问题讨论】:

  • Text = '&lt;%=HTTPContext.Current.User.Identity.Name %&gt;'中的文字是什么
  • 是asp:label控件属性
  • @HOY : 你为什么不在代码后面写标签文本??
  • 将您的文本更改为
  • @huMptyduMpty,我将使用身份名称作为参数,我的意思不是实际设置文本,而是使其工作。

标签: asp.net httpcontext windows-identity


【解决方案1】:
<asp:Label ID="lbUserName" 
           runat="server"
           Text='<%# HttpContext.Current.User.Identity.Name %>'
            />

在 Page_Load 中

if (!Page.IsPostBack )
{
   lbUserName.DataBind();
}

【讨论】:

  • 仍然显示 null (编辑:我的错误)
  • @HOY 你应该检查你的 HttpContext.Current.User.Identity.Name 不为空。上述解决方案应该可以工作
  • 但是同一个问题中的问题呢?数据绑定在这里不起作用stackoverflow.com/questions/9863899/…
【解决方案2】:

这样使用标签

<asp:label id="lblx" runat="server" ><%= HTTPContext.Current.User.Identity.Name %></asp:label>

【讨论】:

    【解决方案3】:

    要像这样绑定文本,您必须创建自己的自定义表达式构建器。

    首先,将这样的类添加到您的命名空间中:

    using System.Web.Compilation;
    using System.CodeDom;
    
    [ExpressionPrefix("Code")]
    public class CodeExpressionBuilder : ExpressionBuilder
    {
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
            object parsedData, ExpressionBuilderContext context)
        {
            return new CodeSnippetExpression(entry.Expression);
        }
    }
    

    下一步是将其添加到您的 web.config 文件中:

    <compilation debug="true">
        <expressionBuilders>
            <add expressionPrefix="Code" type="YourNameSpace.CodeExpressionBuilder"/>
        </expressionBuilders>
    </compilation>
    

    那么最后这应该可以工作了:

    <asp:Label id="YourLabel" runat="server" Text='<%$ Code:HttpContext.Current.User.Identity.Name %>' />
    

    实现简单事物的复杂方法,但这将允许您在整个项目中使用您想要的语法,因此可能值得付出额外的努力。

    Reference.

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 1970-01-01
      • 2014-12-22
      • 2012-04-22
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多