简体   繁体   English

从控制台应用程序中使用Web服务

[英]Consuming a Webservice from a Console Application

I have a web service that creates a JSON package (or whatever you want to call it) like this: 我有一个Web服务,它创建一个JSON包(或任何你想要调用它),如下所示:

 [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void MyMethod(string letters, int number)
        {
            try
            {
                Dictionary<string, object> result = new Dictionary<string, object>();

                //Do some stuff here

                result.Add("data1", 1);
                result.Add("data2", "second value");

                JavaScriptSerializer s= new JavaScriptSerializer();
                Context.Response.Clear();
                Context.Response.ContentType = "application/json; charset=utf-8";
                Context.Response.Flush();
                Context.Response.Write(s.Serialize(result));
            }
            catch (Exception ex)
            {

            }
        }

When I test it I get a nice response like the following: {"data1":1,"data2":"second value."} 当我测试它时,我得到一个很好的响应,如下所示:{“data1”:1,“data2”:“第二个值。”}

Now, the problem is that I've deployed it to a test server and created a simple console application to try make it work. 现在,问题是我已经将它部署到测试服务器并创建了一个简单的控制台应用程序来尝试使其工作。 Here's the application that tries to consume the service. 这是尝试使用该服务的应用程序。 Consider that I added a web reference and named it MyWS, so the namespace and the class have the same name (not what's causing the problem): 考虑我添加了一个Web引用并将其命名为MyWS,因此命名空间和类具有相同的名称(不是导致问题的原因):

class Program
    {
        static void Main(string[] args)
        {
            MyWS.MyWS x = new MyWS.MyWS ();
            x.Timeout = 5000;
            try
            {
                x.MyMethod("Hello World", 1);
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
            }
            Console.ReadLine();
        }


    }

When I run this, I know the web service has been reached. 当我运行它时,我知道已经到达了Web服务。 The "Do some stuff here" part in the WS writes to a database. WS中的“Do some stuff here”部分写入数据库。 It does that, no problem there, so the problem must be after that. 这样做,没有问题,所以问题必须在那之后。

The only error I get is a code 500 with no real meaning. 我得到的唯一错误是没有实际意义的代码500。 Looking around I've found that it could be the .Flush() method, so I deleted that line, and that the Context.Response.BufferOutput should be set to true. 环顾四周我发现它可能是.Flush()方法,所以我删除了那一行,并且Context.Response.BufferOutput应该设置为true。 Did that, didn't work. 那样做了,没用。

Oh, and (probably) to make things worse, the WS will be later consumed by an Android App. 哦,(可能)更糟糕的是,WS将被Android应用程序消耗掉。 But first things first: What am I missing? 但首先要做的是:我错过了什么?

Well, turns out I found the solution on my own after all... well, still browsing the Internet. 好吧,事实证明我毕竟找到了自己的解决方案......好吧,仍在浏览互联网。 Here's the code that works. 这是有效的代码。 Nevermind the variable names in Spanish (I'm Mexican living in Mexico City). 不要用西班牙语(我是生活在墨西哥城的墨西哥人)修改变量名称。 By the way, I found the solution in a forum in Spanish, so it pays off to learn more that your native language. 顺便说一句,我在西班牙语的论坛中找到了解决方案,因此了解更多您的母语是值得的。 =) It's all inside the Main method of the console application. =)它都在控制台应用程序的Main方法中。

string datos = "";

    string url = "http://server.com/wsDirectory/wsFile.asmx/MethodName?param1=value1&param2=value2";
    string respuesta = "";

    try
    {
        byte[] buffer = Encoding.ASCII.GetBytes(datos);
        System.Net.HttpWebRequest solicitud = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
        solicitud.Method = "GET";
        solicitud.ContentLength = buffer.Length;
        System.Net.HttpWebResponse r = (System.Net.HttpWebResponse)solicitud.GetResponse();
        System.IO.Stream datosRespuesta = r.GetResponseStream();
        System.IO.StreamReader lector = new System.IO.StreamReader(datosRespuesta);
        respuesta = lector.ReadToEnd();
        System.Web.Script.Serialization.JavaScriptSerializer serializador = new System.Web.Script.Serialization.JavaScriptSerializer();
        Dictionary<string, object> resultado = (Dictionary<string, object>)serializador.Deserialize<object>(respuesta);
        Console.Write("Resultado obtenido: " + resultado.ToString());

    }
    catch (Exception ex)
    {
        Console.Write(ex.ToString());
    }
    Console.ReadLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM