Saturday, October 20, 2007

User.Identity.Name Returns Empty String in ASP .NET

If you try to get currently logged on user name with User.Identity.Namein ASP.NET, but the return value is empty string.
The following is syntax accesses this variable in C# .NET:

string strUserName = User.Identity.Name;

This problem occurs because if you use Anonymous Access security to access the .aspx page. This problem can also occurs if you give the Anonymous user access in the <authorization> section of the Web.config file.

Solution:
Check the authentication mode in the Web.config file.

If the authentication mode is Forms-based authentication:
<authentication mode="Forms" />
To solve this problem just deny access to the Anonymous user in the Web.config file, user the following syntax:
<authorization>
   <deny users = "?" /> <!-- This denies access to the Anonymous user -->
   <allow users = "*" /> <!-- This allows access to all users -->
</authorization>

If the authentication mode is Windows-based authentication:
<authentication mode="Windows" />
To solve this problem, use the following steps:

1. Go to Internet Services Manager, right-click the .aspx file or the Web Project folder, and then click Properties.
2. If you clicked Properties for the Web Project folder, click the Directory Security tab. If you clicked Properties for the .aspx file, click the File Security tab.
3. Under Anonymous Access and authentication control, click Edit.
4. In the Authentication methods dialog boc, clear the Anonymous Access check box, and then select either theBasic, the Digist or the Integrated (NT Challenge/Response) check box.
6. Click OK to close both dialog boxes.


No comments: