Aviadjo
Aviadjo

Reputation: 655

Asp.net search Active Directory from IIS

Recently I moved my ASP.NET application from an old server running IIS5 to a new server running IIS7.5.

The application gives me an error:

The (&(objectCategory=person)(sAMAccountName=)) search filter is invalid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: The (&(objectCategory=person)(sAMAccountName=)) search filter is invalid.

The function that searches AD is:

public static string Get_AD_User_Email(string username)
{
        try
        {
            DirectorySearcher searcher = new DirectorySearcher("(&(objectCategory=person)(sAMAccountName=" + username + "))");
            SearchResult result = searcher.FindOne();

            if (result != null)
            {
                DirectoryEntry employee = result.GetDirectoryEntry();

                if (employee.Properties["mail"] != null)
                {
                    return employee.Properties["mail"].Value.ToString();
                }
                else return "NULL";
            }
            else throw new Exception("ERROR: Problem searching active directory for users.");
        }
        catch (Exception ex) { throw ex; }
    }

The weird thing is that on debug in Visual Studio the website is running, only from IIS it's crashes.

Can someone help me?

Upvotes: 3

Views: 1760

Answers (4)

Peter
Peter

Reputation: 9712

You changed IIS servers, now no username is being passed in by the calling method (as several other answers point out).

I would verify that you have anonymous access disabled on that website in IIS. It's common to find both Windows authentication and anonymous access enabled. When this happens anonymous is preferred and you won't get the username.

Check the value of HttpContext.Current.User. I usually use code like the one below to verify windows authentication:

WindowsIdentity id = (WindowsIdentity)HttpContext.Current.User.Identity; 
string username = id.Name;

Upvotes: 1

Daro
Daro

Reputation: 2020

Since:

DirectorySearcher searcher = new DirectorySearcher("(&(objectCategory=person)(sAMAccountName=" + username + "))");

Is returning the exception:

The (&(objectCategory=person)(sAMAccountName=)) search filter is invalid.

You are passing an empty string to Get_AD_User_Email.

How are you retrieving "username"?

Upvotes: 1

JPBlanc
JPBlanc

Reputation: 72680

The trouble is just that your function Get_AD_User_Email(string username) is called with an empty value for username.

Upvotes: 2

Roger
Roger

Reputation: 1

Try: objectClass=user

Instead of: objectCategory=person

Upvotes: -1

Related Questions