Search code examples
exchangewebservicesrestsharpwebrequestntlm

C# WebRequest to a URL that is configured for Windows Authentication


I am trying to get user photos out of Microsoft Exchange using the GetUserPhoto REST request documented here: https://msdn.microsoft.com/en-us/library/office/jj190905%28v=exchg.150%29.aspx?f=255&MSPPError=-2147217396

My problem is no matter what I do the connection gets closed automatically and it can't authenticate using NTLM. Microsoft even provides code but when you run this in a IIS web application even if it is using an application pool running as a domain user, it never can authenticate.

This is my current code that isn't working:

request = System.Net.WebRequest.Create($"https://{Settings.ExchangeServer}/ews/exchange.asmx/s/GetUserPhoto?email={primarySmtpAddress}&size=HR240x240") as System.Net.HttpWebRequest;

                        request.ServerCertificateValidationCallback = delegate { return true; };
                        request.UseDefaultCredentials = true;
                        resp = request.GetResponse() as System.Net.HttpWebResponse;

Now I can put this in a console application and run it and then it works. But in IIS it just won't work at all. I've even tried RestSharp with no luck.


Solution

  • The problem was it wasn't trying to connect with TLS 1.2. Once it clicked in my head, the error message was saying the connection closed and not actually returning a 401. I user ServiceManager to set it to TLS1.2 and then it started working.

    Glen Scales help point me in the right direction though to troubleshoot it further.