HTTPContext.Current.User.Identity.Name not working inside a control?

て烟熏妆下的殇ゞ 提交于 2019-12-25 17:01:25

问题


I have a label and I want to set text of this label to

HTTPContext.Current.User.Identity.Name

So I wrote

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

but it doesn't work, however when I wrote this outside of the lable for example:

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

it works.


回答1:


<asp:Label ID="lbUserName" 
           runat="server"
           Text='<%# HttpContext.Current.User.Identity.Name %>'
            />

in Page_Load

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



回答2:


use label like this

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



回答3:


To bind the text like this you will have to create your own custom expression builder.

First, add such class to your namespace:

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

Next step is adding this to your web.config file:

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

Then finally this should work:

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

Complicated way to achieve something simple, but this will allow you to use the syntax you want throught your whole project so might worth the extra effort.

Reference.



来源:https://stackoverflow.com/questions/9786750/httpcontext-current-user-identity-name-not-working-inside-a-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!