从c#调用asp.net服务时出现401错误

时间:2013-07-11 12:33:50

标签: c# asp.net service web http-status-code-401

我一直坚持这一点,从c#服务器端代码调用asp.net Web服务时,我一直收到401错误。 Web服务托管在远程服务器上,我从配置文件(Wrapper Service)获取其地址。每当我调用它时,即使我可以从Web浏览器调用Web服务方法,我也会收到401错误。这是代码:

    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;
        }
    }

0 个答案:

没有答案