SOAP请求从Windows服务失败

时间:2010-07-29 23:53:45

标签: c# soap

我正在使用以下代码创建SOAP请求

    public static string SubmitSoapRequest(string url,
                                                        string ns,
                                                        string operation,
                                                        string requestXml,
                                                        bool responseNodeOnly)
    {
        // make sure the namespace has a trailing slash
        ns = ns.TrimEnd('/') + '/';

        // format soap request
        string soap = string.Format(SOAP_REQUEST_XML, ns, operation, requestXml);

        // format soap action
        string soapAction = string.Format(@"{0}{1}", ns, operation);

        // initialize web request
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

        // add header and other soap params
        req.Headers.Add("SOAPAction", soapAction);
        req.ContentType = @"text/xml;charset=""utf-8""";
        req.Accept = "text/xml";
        req.Method = "POST";

        // make soap request
        using (Stream s = req.GetRequestStream())
        using (StreamWriter sw = new StreamWriter(s))
            sw.Write(soap);

        // get response from remote web-service
        WebResponse response = req.GetResponse();

从已编译的Windows应用程序运行时可以正常工作,但从Windows服务调用时失败。从例外中捕获'500内部服务器错误'。

有没有理由为什么通过Windows服务运行可能导致这个?

提前感谢任何帮助/建议

1 个答案:

答案 0 :(得分:0)

在没有看到服务发生了什么的情况下,我最初的猜测是它的凭据相关。远程服务是否需要特定凭据才能访问?当您将代码作为Windows应用程序运行时,传递给服务的凭据可能是您的网络凭据;但该服务正在传递其凭据(网络服务)。

您可能希望在发出服务请求之前在请求中设置相应的凭据。这是我下车的例子MSDN

CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(new Uri("http://foo.com/"),"Basic", new NetworkCredential("user1","passwd1","domain1"));
WebRequest myWebRequest = WebRequest.Create("http://foo.com");
NetworkCredential myCredential = myCredentialCache.GetCredential(new Uri("http://foo.com"),"Basic");
myWebRequest.Credentials = myCredential; 
WebResponse myWebResponse = myWebRequest.GetResponse();

在没有看到服务的情况下,这将根据您描述的情况进行初步调查。我希望这有帮助!!