0

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

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

0 回答 0