【问题标题】:Calling a web service method using httpwebrequest - Unable to connect to the remote server error使用 httpwebrequest 调用 Web 服务方法 - 无法连接到远程服务器错误
【发布时间】:2012-04-24 23:57:23
【问题描述】:

我正在调用我的 Web 服务的特定方法,但是一旦我创建了一个新的 StreamWriter 对象,就会出现上述错误。我不确定为什么会发生这种情况,因为我以前从未这样做过。我用来执行此操作的代码是使用此链接编写的 - Invoking an ASP.NET web service method via an http request 作为参考。这是sn-p -

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/Helpers/Symbology.asmx");
httpWebRequest.Headers.Add("SOAPAction", "\"http://tempuri.org/GetRelatedSymbols\"");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
JavaScriptSerializer serializer = new JavaScriptSerializer();

*using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))*//error occurs here
{
    string json = serializer.Serialize(relatedSymbols);
    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string responseText = String.Empty;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     responseText = streamReader.ReadToEnd();
}

这是我的网络服务代码的 sn-p -

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Symbology: System.Web.Services.WebService
{

    [WebMethod]
    public List<string> GetRelatedSymbols()
    {
        try
        {
             //code here
        }
        catch(){}
    }
}

谁能帮忙指出我做错了什么?

【问题讨论】:

  • 网站是从哪里托管的?
  • 目前,我想让它在我的本地主机上运行。
  • @neuDev33:不,我的意思是你现在在哪里托管它?它必须在 VS 开发服务器或 IIS 等中运行才能向它发出 Web 请求。
  • 这意味着您没有在 localhost 上设置 Web 服务。如果你这样做,它应该可以工作。
  • 如果你只是在调试模式下运行 Visual Studio,然后检查你会看到它正在运行。但是,当您在 Visual Studio 中停止调试时,它就不再运行并且无法被其他地方访问。例如,您需要在 IIS 中托管它,或者在您的计算机上保持 Visual Studio 调试处于打开状态。

标签: c# web-services httpwebrequest


【解决方案1】:

当我运行网络服务器时,我总是需要使用这样的 URL 进行连接 http://localhost:PORTNUMBER/...

【讨论】:

  • 这不起作用。真正的问题是我没有托管我的网络服务。
【解决方案2】:

我刚刚发布了一个关于多个启动项目的答案,以解决另一个关于网站使用 Web 服务的问题。

这里有一些说明... Web Reference Help: No connection could be made because the target machine actively refused it

这假设您的两个启动项目都在同一个解决方案中。

【讨论】:

    猜你喜欢
    • 2010-11-04
    • 2016-10-13
    • 2011-04-19
    • 1970-01-01
    • 2014-06-21
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多