How to utilize ASP.NET current user name in SqlParameter without code-behind

How do I get to the current users name without doing it in the code-behind, just using the aspx server tags?

In code-behind I can just do this:

Label4.Text = User.Identity.Name.ToString()

But I’m trying to do it without code-behind like this:
<body>
    <form id="form1" runat="server">
    <div>
        1. <asp:Label ID="Label1" runat="server" Text="<% User.Identity.Name %>"/><br />
        2. <asp:Label ID="Label2" runat="server" Text="<%= User.Identity.Name %>"/><br />
        3. <asp:Label ID="Label3" runat="server" Text="<%# User.Identity.Name %>"/><br />
        4. <asp:Label ID="Label4" runat="server" Text="<%= Context.User.Identity.Name %>"/><br />
        5. <asp:Label ID="Label5" runat="server" Text='<%# User.Identity.Name %>' /><br />
        6. <span runat="server" ID="Span1"><%= User.Identity.Name %></span><br />
        7. <asp:LoginName ID="LoginName1" runat="server" /><br />
        8. <span><%# User.Identity.Name %></span><br />
        9. <span><%= User.Identity.Name %></span><br />
        10. <asp:Label ID="Label6" runat="server" Text='<%= User.Identity.Name %>' /><br />
    </div>
    </form>
</body>

I get the username displayed for lines 6, 7, and 9 but I really want to set a property of a control to this value and not just display it on screen.

Is it possible?

Background: I was whipping up a quick app, dragging and dropping controls on the page, and it turned out that I did it with only having 1 line in code-behind of the page(s). That line was setting the value of a hidden field to the current users name in page load so I could pass the value of that control as a param of a sqlparameter. So I thought that since I was going this route (lots of stuff in aspx that maybe shouldn’t be there) I should try to be consistent with it. I don’t normally do it this way, but wanted to this time

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In a comment you wrote:

Also, if I could get any controls
value set to this username I could
then specify my sqlparameter is a
controlparameter and that would get me
where I need to be too.

You can create a custom parameter type.

Start by creating this class, either in App_Code or in a ASP.NET Server control dll:

namespace ParameterDemo {
    public class LoginParameter : Parameter {
        public LoginParameter(string name)
            : base(name)
        {}

        protected override object Evaluate(HttpContext context, Control control)
        {
            //UPDATED as suggested in Joels comments below...
            //return HttpContext.Current.User.Identity.Name;
            return context.Current.User.Identity.Name;
        }
    }
}

and registering it on the page (right after the @Page directive)
<%@ Register TagPrefix="put" Namespace="ParameterDemo" %>

(or optionally register it in web.config for use on all pages)

…and the you can use it like this:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    SelectCommand="SELECT * FROM MyTable WHERE <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6e5d9dbd3e0d7dac3d38bf6e5d9dbd3e6d7c4d7dbd3c2d3c4">[email protected]</a>">
    <SelectParameters>
        <put:loginParameter name="SomeParameter" />
    </SelectParameters>
</asp:ObjectDataSource>

If this is what you’re looking for, you should consider editing the original question…

Method 2

If you really want to pass the current user name as a select parameter to SqlDataSource, I’d suggest making a quick custom parameter (either as a code file in your web project or in a separate assembly if you like):

namespace CustomParameters
{
    public class UserNameParameter : Parameter
    {
        public UserNameParameter()
        {
        }

        public UserNameParameter(string name)
            : base(name)
        { }


        protected override object Evaluate(HttpContext context, Control control)
        {
            return User.Identity.Name;
        }
    }
}

and then in your page:
<%@ Register TagPrefix="myNS" Namespace="CustomParameters" %>

...

<myNS:UserNameParameter Name="UserName" />

Method 3

Do you really need it in a label server control? Or could you just use the span tags rendered by the server control?

<span runat="server" ID="Label2"><%= User.Identity.Name %></span>

Update:
Okay, new goal: Get User.Identity.Name into an SqlParameter value without using the codebehind.

This is going to be tricky. The basic code tag bee-stings (<% %> and the like) don’t run in the page life cycle until after your query was already executed. That means you need to handle an earlier page life cycle event yourself, and the usually means putting something in the code behind. If you really want to get rid of the code-behind you can of course include a server-side script on your page:

<%@ Page Lanuage="C#" %>
<script runat="server" language="c#">
    public void OnSelecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
       e.Command.Parameters["@UserName"].Value = User.Identity.Name;
    }
</scirpt>
<html>
<body>
    <asp:SqlDataSource runat="server" ID="MyDataSource" OnSelecting="OnSelecting" ...>
    <SelectParameters>
        <asp:Parameter Name="UserName" ... />
    </SelectParameters>
    </asp:SqlDataSource>

    <asp:GridView runat="server" ID="ResultsGrid" DataSourceID="MyDataSource" .../>

</body>
</html>

It’s still writing real code, though, rather than keeping everything in markup. But I suspect it’s the closest you can get here.

Method 4

Will this do the trick?

<asp:LoginName ID="LoginName1" runat="server" />

Method 5

I’m not sure about this but,i think

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

Double quotes is not a true for expressions when defined in a property.
Instead of using above expression you may also print value in some html label with just writing your expression i.e.
<span><%# User.Identity.Name %></span>

And make sure that you authenticated user well enough.

Method 6

Don’t use a self closing label.

<asp:Label ID="UserNameLabel" runat="server" ><%= My.User.Name %></asp:Label>

Method 7

<asp:Label ID="Label1" runat="server" Text='<%= User.Identity.Name %>' />

The problem is the double quotes. You will often need to use single quotes

Method 8

One way would be to set it in the code behind:

Label1.Text = User.Identity.Name.ToString();

Another way would be to use an expression builder, such as Ricardo Peres’s CodeExpressionBuilder, to bind a control property from the aspx markup:
<asp:Label runat="server" Text="<%$ Code: User.Identity.Name.ToString() %> />

Method 9

I suspect that you forgot to call DataBind() on your form. Label3 or Label5 should work perfectly.

Add a call to form1.Databind() in your Page_Load() and that should fix it.

Method 10

You can use a Profile parameter instead:

<asp:ProfileParameter Name="SomeParameter" PropertyName="UserName" Type="String" />

Method 11

Some possible answers above, but another possible option is to use Windows Authentication on the web server and disable anonymous access. Windows users are authenticated automatically if the website is set as local intranet.

In your SQL connection, use: Integrated Security=True

The important part is to add the following to the web.config:

<system.web>
  <identity impersonate="true" />
</system.web>

Without the impersonate in the web.config, your database connections will be authenticated via the user defined in the app pool: IIS APPPOOLASP.NET v4

Then inside SQL you can use the CURRENT_USER function to read the User, thus not requiring to pass a current user via a stored procedure.

Tom


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x