Home > front end >  C# WebService: server can't process the request
C# WebService: server can't process the request

Time:12-16

I'm trying to send a JSON message to WebService maked with ASP.NET Web Application (.NET Framwork) in Visual Studio 2022. However, I receive the next exception when I try to send a message with the POST method. But if I try to send to JSONPlaceholder free fake rest api it works correctly.

Hello, World!
Send msg:
Hello_World.
=====
{"Transmission":"Hello_World"}
=====
Response:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="es">System.Web.Services.Protocols.SoapException: El servidor no puede procesar la solicitud. ---&gt; System.Xml.XmlException: Los datos del nivel de raíz no son válidos. línea 1, posición 1.
   en System.Xml.XmlTextReaderImpl.Throw(Exception e)
   en System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   en System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   en System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
   en System.Xml.XmlReader.MoveToContent()
   en System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
   en System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
   en System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   en System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean&amp; abortProcessing)
   --- Fin del seguimiento de la pila de la excepción interna ---</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>

Does anyone know how to correctly accept POST requests in an Web Service ASMX?

My client program is:

    private static async Task Main (string[] args) {
    
        Console.WriteLine("Hello, World!");
    
        try {
    
            /*
              * Check web service created locally.
              * string wsUrl = "https://localhost:44373/SoapDemo.asmx";
              * string wsUrl = "https://jsonplaceholder.typicode.com/posts";
          */
        string wsUrl = "https://localhost:44373/SoapDemo.asmx";

        // Send a small string.
        string msg = "Hello_World";
        Console.WriteLine("Send msg:\n{0}.", msg);

        // Create connection to Web Service.
        var client = new HttpClient();

        // Prepare the data to send to WS.
        Post postMsg = new Post();
        postMsg.Transmission = msg;
        var data = JsonSerializer.Serialize<Post>(postMsg);

        // Finally send the msg to the WebService.
        Console.WriteLine("=====\n"   data   "\n=====");
        HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json"); 

        // Recive a response from the Web Service server.
        var httpResponse = await client.PostAsync(wsUrl, content);

        // if (httpResponse.IsSuccessStatusCode) {

            var result = await httpResponse.Content.ReadAsStringAsync();
            Console.WriteLine("Response:\n{0}", result);
            // var postResult = JsonSerializer.Deserialize<Post>(result);
            // Console.WriteLine("Response:\n{0}", postResult);

        // }

    }

    catch (Exception ex) {

        Console.WriteLine("Transmission error:\n{0}", ex.ToString());

    }

}

And my Web Service ASMX function:

[WebMethod]
    // [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public bool Transmission () {

        ABCObject ObjectName = null;
        string contentType = HttpContext.Current.Request.ContentType;

        if (false == contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) {

            return false;

        }

        using (System.IO.Stream stream = HttpContext.Current.Request.InputStream)
        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream)) {

            stream.Seek(0, System.IO.SeekOrigin.Begin);
            string bodyText = reader.ReadToEnd();
            bodyText = bodyText == "" ? "{}" : bodyText;
            var json = Newtonsoft.Json.Linq.JObject.Parse(bodyText);
            ObjectName = Newtonsoft.Json.JsonConvert.DeserializeObject<ABCObject>(json.ToString());

        }

        return true;

    }

I have taken this ASMX solution from Accepting a json request with a Webservice (asmx).

Could someone give me a hand? Thank you very much for the help

)

CodePudding user response:

As @Panagiotis Kanavos rightly says, this is obsolete. However, I found a more comfortable way to communicate with an ASMX service.

  1. Add a connected service to project (in Visual Studio).
  2. Import the service in your code.
  3. Call the next functions to use this ASMX service.
YourServiceSoapClient ws = new YourServiceSoapClient(YourServiceSoapClient.EndPointConfiguration.YourServiceSoap);

// Call the ASMX service functions.
string wsHelloWorld = ws.HelloWorld();
Console.WriteLine(wsHelloWorld);

I am attaching some links in case anyone wants to do some research.

  • Related