I created a web service hosted in SharePoint 2010 and I want to unit test its behaviour/results. Now when I try to run a test with a different user, I always get the results of the previous user and my test fails.
I can see in fiddler that for subsequent requests no authentication is happening:
My implementation of the webclient throws away all cookies, so why is there no re-auth?
I am passing different credentials to the HttpWebRequest.Credentials property because I use NTLM.
Update 1:
private CookieContainer container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = null;
}
return request;
}
public string HttpPost(string URI, Dictionary<string, object> data, NetworkCredential credentials)
{
HttpWebRequest req = (HttpWebRequest)GetWebRequest(new Uri(URI));
if (credentials != null)
{
req.Credentials = credentials;
req.UseDefaultCredentials = false;
}
else
{
req.UseDefaultCredentials = true;
}
//Add these, as we're doing a POST
req.ContentType = "application/json; charset=UTF-8";
req.Method = "POST";
this.Encoding = Encoding.UTF8;
this.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=UTF-8");
this.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
this.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
this.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
if (data != null)
{
string json = JsonConvert.SerializeObject(data, new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Local,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(json);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
}
else
{
req.ContentLength = 0;
}
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}