Mensaje dentro de Servicios Webs

Responder 
#1 - 21/04/2015 16:50:34 Reporta abuso | Link Permanente
web service asíncrono
Usuario no registrado
¿Cómo puedo crear un web service asíncrono en ASP.NET usando el método AsyncCallback?

Responder Citar

Buenas,

Estoy intentando crear un web service asíncrono en ASPNET usando el método "AsyncCallback", pero estoy recibiendo un error en el método "RespCallback" cuando llamo al "EndGetResponse":

The remote server returned an error: (500) Internal Server Error.

Estoy intentando hacerlo con sencillo ejemplo: Hello World.

Éste es el código de mi servidor:

[WebService]public class WebService : System.Web.Services.WebService {       public delegate string HelloWorldAsyncStub(        string text);    public string HelloWorld(string text)    {        return "Hello " + text;    }        public class MyState    {        public object previousState;        public HelloWorldAsyncStub asyncStub;    }    [WebMethod]    public IAsyncResult BeginHelloWorld(string name, AsyncCallback cb, object s)    {        HelloWorldAsyncStub stub = new HelloWorldAsyncStub(HelloWorld);        MyState ms = new MyState();        ms.previousState = s;        ms.asyncStub = stub;        return stub.BeginInvoke(name, cb, ms);    }    [WebMethod]    public string EndHelloWorld(IAsyncResult call)    {        MyState ms = (MyState)call.AsyncState;            return ms.asyncStub.EndInvoke(call);    }    }

Éste es el código del cliente:

class Program    {        static private WebRequest Webrequest;            static byte[] byteArray;            const int BUFFER_SIZE = 1024;            static Stream dataStream = null;            static ManualResetEvent allDone = new ManualResetEvent(false);            static void Main(string[] args)            {                try                {                    Webrequest = WebRequest.Create("http://localhost/TestService/");                    Webrequest.ContentType = "text/xml";                    Webrequest.Method = WebRequestMethods.Http.Post;                    //if there are pending requests xmlRequestPending                    byteArray = System.Text.Encoding.UTF8.GetBytes("World");                    Webrequest.ContentLength = byteArray.Length;                    dataStream = Webrequest.GetRequestStream();                    dataStream.Write(byteArray, 0, byteArray.Length);                    RequestState rs = new RequestState();                    rs.Request = Webrequest;                    IAsyncResult r = (IAsyncResult)Webrequest.BeginGetResponse(new AsyncCallback(RespCallback), rs);                    Console.ReadLine();                }catch(Exception e)                {                }            }            static private void RespCallback(IAsyncResult ar)        {            try            {                // Get the RequestState object from the async result.                RequestState rs = (RequestState)ar.AsyncState;                // Get the WebRequest from RequestState.                WebRequest req = rs.Request;                // Call EndGetResponse, which produces the WebResponse object                //  that came from the request issued above.                WebResponse resp = req.EndGetResponse(ar);                //  Start reading data from the response stream.                Stream ResponseStream = resp.GetResponseStream();                // Store the response stream in RequestState to read                 // the stream asynchronously.                rs.ResponseStream = ResponseStream;                //  Pass rs.BufferRead to BeginRead. Read data into rs.BufferRead                IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0,                   BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);            }            catch (Exception exc)            {            }        }            static private void ReadCallBack(IAsyncResult asyncResult)            {                try                {                    // Get the RequestState object from AsyncResult.                    RequestState rs = (RequestState)asyncResult.AsyncState;                    // Retrieve the ResponseStream that was set in RespCallback.                     Stream responseStream = rs.ResponseStream;                    // Read rs.BufferRead to verify that it contains data.                     int read = responseStream.EndRead(asyncResult);                    if (read > 0)                    {                        // Prepare a Char array buffer for converting to Unicode.                        Char[] charBuffer = new Char[BUFFER_SIZE];                        // Convert byte stream to Char array and then to String.                        // len contains the number of characters converted to Unicode.                        int len =                           rs.StreamDecode.GetChars(rs.BufferRead, 0, read, charBuffer, 0);                        String str = new String(charBuffer, 0, len);                        // Append the recently read data to the RequestData stringbuilder                        // object contained in RequestState.                        rs.RequestData.Append(                           Encoding.ASCII.GetString(rs.BufferRead, 0, read));                        // Continue reading data until                         // responseStream.EndRead returns –1.                        IAsyncResult ar = responseStream.BeginRead(                           rs.BufferRead, 0, BUFFER_SIZE,                           new AsyncCallback(ReadCallBack), rs);                    }                    else                    {                        if (rs.RequestData.Length > 0)                        {                            //  Display data to the console.                            string strContent;                            strContent = rs.RequestData.ToString();                        }                        else                        {                        }                    }                    // Close down the response stream.                    responseStream.Close();                    // Set the ManualResetEvent so the main thread can exit.                    allDone.Set();                }                catch (Exception e)                {                }            }        internal class RequestState        {            const int BufferSize = 1024;            public StringBuilder RequestData;            public byte[] BufferRead;            public WebRequest Request;            public Stream ResponseStream;            // Create Decoder for appropriate enconding type.            public Decoder StreamDecode = Encoding.UTF8.GetDecoder();            public RequestState()            {                BufferRead = new byte[BufferSize];                RequestData = new StringBuilder(String.Empty);                Request = null;                ResponseStream = null;            }        }    }

El web service está publicado en mi máquina local:"http://localhost/TestService/".

Además, he estado intentando debugar el código del web service para ver qué está pasando, pero todavía no he sido capaz de hacerlo.

¿Puede alguien ayudarme por favor? He pasado muchas horas intentando encontrar una solución para esto pero no he encontrado nada.

Muchas gracais a todos.

Volver arriba