I've been stuck on this for quite a bit, I keep getting a 401 error when calling an asp.net web service from c# server side code. Web service is hosted on a remote server, I get its address from config file (Wrapper Service). Whenever I call it, I get a 401 error, even though I can invoke web service method from web browser. Here's the code:
private string getCode(string name)
{
XmlDocument xmlResponse = new XmlDocument();
string request = getRequestXML(name);
string response = ExecuteRequest(request);
if (response != "")
{
xmlResponse.LoadXml(ExecuteRequest(request));
return xmlResponse.GetElementsByTagName("roaming")[0].InnerText;
}
else
{
return "error getting password";
}
}
private string getRequestXML(string userName)
{
var sr = "<?xml version='1.0' encoding='utf-8'?>"+
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"+
"<soap:Body>"+
"<GetAccountInfo xmlns='http://tempuri.org/'>"+
"<loginName>"+userName+"</loginName>"+
"</GetAccountInfo>"+
"</soap:Body>"+
"</soap:Envelope>";
return sr;
}
private string ExecuteRequest(string soapStr)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["WraperService"]);
req.Headers.Add("SOAPAction", "\"http://tempuri.org/" + "GetAccountInfo" + "\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soapStr);
}
}
using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()))
{
string result = responseReader.ReadToEnd();
//XDocument ResultXML = XDocument.Parse(result);
return result;
}
}