.net core web service asmx

How to Run Web Services (.asmx) As An API

Matt 2020/12/02 01:34:06
2678

What is Web Service ?

  • A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. As all communication is in XML, web services are not tied to any one operating system or programming language—Java can talk with Perl; Windows applications can talk with Unix applications.

  • Web services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

  • Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.

  • A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.

Basic Knowledge

In another way, it's (web service) a http request to post xml data to a web service.

Choose a web service function (or operation), and observe it

img "web service op xml"

Look at the red line marks, it marked our xml data to post out. The SOAP envelope xml data based on web service functions.

Envelope for SOAP 1.1

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <wsYourFunction xmlns="http://www.xyz.com.tw/web Services">
      <columnA>string</columnA>
      <columnB>string</columnB>
      <columnC>string</columnC>
    </wsYourFunction>
  </soap:Body>
</soap:Envelope>

Envelope for SOAP 1.2

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <wsYourFunction xmlns="http://www.xyz.com.tw/web Services">
      <columnA>string</columnA>
      <columnB>string</columnB>
      <columnC>string</columnC>
    </wsYourFunction>
  </soap12:Body>
</soap12:Envelope>

Send xml via HttpClient

var httpClient = new HttpClient();
var req = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://YourWebService.asmx"),
    Content = new StringContent(xml, System.Text.Encoding.UTF8, "text/xml") // the Content-Type
};

the Content-Type, it depends on your web services located server's programming, it might be worked with application/xml, instead of text/xml.

Workshop

Since we have a basic knowledge of SOAP, we can now, to make it as an api call.

-Create a soapService

Our goal is making a service about sending xml data through web service, and grab its response.

Buckle up. Let's try it.

public class SoapService
{
    private readonly HttpClient _httpClient;

    public SoapService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public string Login(string coAccount, string account, string password)
    {
        var xml = MakeSoapEnvelope("<wsCheckAC xmlns=\"http://www.xyz.com.tw/web Services\">" +
            $"<CoAccount>{coAccount}</CoAccount>" +
            $"<Account>{account}</Account>" +
            $"<Password>{password}</Password></wsCheckAC>");

        var req = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri("https://your_web_service.asmx"),
            Content = new StringContent(xml, System.Text.Encoding.UTF8, "text/xml")
        };

        // grab response
        var resp = _httpClient.SendAsync(req).GetAwaiter().GetResult();
        var content = resp.Content.ReadAsStringAsync().GetAwaiter().GetResult();

        return GetResultFromResponse(content);
    }

    private static string MakeSoapEnvelope(string bodyXml, bool isSoap12 = true)
    {
        return isSoap12
            ? $"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"><soap12:Body>{bodyXml}</soap12:Body></soap12:Envelope>"
            : $"<?xml version=\"1.0\" encoding=\"utf-16\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body>{bodyXml}</soap:Body></soap:Envelope>";
    }

    private static string GetResultFromResponse(string content)
    {
        var ret = string.Empty;
        using var reader = XmlReader.Create(new StringReader(content));
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    if (reader.Name == "wsCheckACResult")
                    {
                        var el = XNode.ReadFrom(reader) as XElement;
                        ret = el.Value;
                    }
                    break;
            }
        }
        return ret;
    }
}

-Register soapService before using it

For the api controller calling, we need to register HttpClient in Startup first.

services.AddHttpClient<SoapService>();

It will inject HttpClient instance into SoapService when we need it.

-Implement api controller

Final step, to build an api controller calling web services.

[Route("api/[controller]")]
[ApiController]
public class SoapDemoController : ControllerBase
{
    private readonly SoapService _soapService;

    public SoapDemoController(SoapService soapService)
    {
        _soapService = soapService;
    }

    [HttpGet, Route("login")]
    public IActionResult CheckLogin()
    {
        try
        {
            var state = _soapService.Login("demo", "demo", "demo");
            return Ok(state);
        }
        catch
        {
            throw;
        }
    }

    [HttpGet, Route("login/{coAccount}/{account}/{password}")]
    public IActionResult CheckLogin(string coAccount, string account, string password)
    {
        try
        {
            var state = _soapService.Login(coAccount, account, password);
            return Ok(state);
        }
        catch
        {
            throw;
        }
    }
}

When api called, we will see the response result of web service.

-call from browser

img "api call -browser,code"

-call by postman

img "api call -postman"

Enjoy it.


References:

What are Web Services?

簡單四步驟:使用ASP.NET Core提供口罩剩餘數量查詢API

HttpClient Class

使用 HttpClient 來存取 GET,POST,PUT,DELETE,PATCH 網路資源

Several Ways To Send Request And Get Response Via HttpClient

Matt