views:

370

answers:

2

How does one get the logged in user name using jquery?

I am using ASP.Net and have been doing it in code behind like this:

System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString();

I am trying to authenticate a user using the login domain name and use a web service to authenticate.

<script type="text/javascript">
    //<![CDATA[
$(document).ready(function() {

    $.ajax({ type: "POST",
    url: "DemoWebService.asmx/GetFulName",
    dataType: "xml",
    data: "networkId=" + arg1,
        processData: false,
        error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
        success: function(xml) { ajaxFinish(xml); }
    });

});
    function ajaxFinish(xml) {
        // parse the object
    }

    function ajaxError(xmlObj, textStatus, errorThrown) {
        // Comment this out for live environments, and put a friendly error message
        alert("(Ajax error: " + txt + ")");
        alert(request.responseText);
    }

//]]>
</script>


[WebMethod]
public string GetFulName(string networkId)
{
    return networkId + "Full Name";
}
+1  A: 

You could set a javascript variable in your aspx markup with the username like so:

<script type="text/javascript">
    var username = "<%= User.Identity.Name %>";
</script>

See http://msdn.microsoft.com/en-us/library/system.security.principal.iidentity_members.aspx for more information on User.Identity.Name.

jrummell
Thanks for your response.Error 3 The name 'User' does not exist in the currentI get the above error.
Picflight
User is a property of System.Web.UI.Page. Did you try this in an .aspx page?
jrummell
+1  A: 

Since the Auth_User server variable was not working on the client, I am able to change my WebMthod to get the logged in user name:

[WebMethod]
public string GetFulName(string networkId)
{
    //return networkId + " Full Name";
    return networkId + " From Server: " + System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString();
}
Picflight