1

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

)

F A Fernández
  • 101
  • 1
  • 8
  • 2
    Don't create such a web service in the first place. ASMX is an ancient framework for SOAP services, replaced by WCF in 2008. SOAP uses XML, not JSON. Yes, Microsoft did try to make them work with JSON as a stop-gap measure until ASP.NET MVC was introduced. Right now you've written a ton of code to do what a Minimal API and PostAsJsonAsync would do in 10-15 lines – Panagiotis Kanavos Dec 13 '22 at 18:42
  • The JSON format is a client requirement. I guess I could get it to work on JSON format with _Newtonsoft_ or _System.Text.Json_ maybe? – F A Fernández Dec 14 '22 at 14:34
  • If you want JSON, don't use ASMX. ASMX is for SOAP, not JSON – Panagiotis Kanavos Dec 14 '22 at 15:20
  • I explained myself wrong: I have to send a JSON with x information to a web service, and next they are going to send me a different JSON. I created a WebService with SOAP because I saw that they did it like this and it was the most handy documentation, but I have problems sending the JSON packet and receiving a response. My question was more like how could I communicate with a webservice and make it send me a JSON response with POST. Thank you and sorry for the inconvenience, I have never worked with Microsoft Web Service services. – F A Fernández Dec 14 '22 at 15:45
  • You had do dig pretty deeply to find those docs because people simply stopped using ASMX for this over 10 years ago. For ASP.NET Core, check [Tutorial: Create a minimal web API with ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-7.0&tabs=visual-studio) or [Tutorial: Create a web API with ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-7.0&tabs=visual-studio). I wasn't joking when I said you need 10-15 lines to do what you want – Panagiotis Kanavos Dec 14 '22 at 16:12
  • Thanks for the tutorial, it's quite useful, but the client wants me to send the data by: api rest, socket and asmx. It's a client requirement, and I doesn't decide this. My ask is: how to send a soap (sorry about this i got confused when I writed this question) to WebService ASMX? Thanks for the help and sorry for my incorrections. – F A Fernández Dec 15 '22 at 11:06

1 Answers1

0

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.

F A Fernández
  • 101
  • 1
  • 8