简体   繁体   中英

asp.net webservices (.asmx)

Internally webservices use soap to work over HTTP. But when we try to access a [WebMethod] of a web service, how things start working on the basis of URL with jquery ajax? Does SOAP still playing the role with jQuery ajax? If yes how? If not why not? You can use below example to keep thing simple.

Below is the code from asmx:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {          
        return "Hello World";
    }
}

It is possible to call WebMethods with AJAX as the transport is HTTP . You can find many examples of it in the internet and on SO:

jQuery AJAX call to an ASP.NET WebMethod

Calling ASP.Net WebMethod using jQuery AJAX

SOAP is an envelope for the payload (with some additional features). It is up to you whether you want to use it in WebMethod or not.

Here is how you create a Hello World service in web application project:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

Here is how you can consume it with jQuery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

<script>
    console.log($.ajax);
    $.ajax({
        type: "POST",
        url: "http://localhost:55501/WebService1.asmx/HelloWorld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response.d) {
            alert(response.d);
        }
    });
</script>

And response from server will be {d: "Hello World"} because jQuery will add Accept header "application/json".

Here is how you can consume it from console app:

static void Main(string[] args)
{
    var client = new HttpClient();
    var uri = new Uri("http://localhost:55501/WebService1.asmx/HelloWorld")

    // Get xml
    var response = client.PostAsync(uri, new StringContent("")).Result;
    Console.WriteLine(response.Content.ReadAsStringAsync().Result);

    Console.WriteLine();

    // Get Json
    var response1 = client.PostAsync(uri,
        new StringContent("", Encoding.UTF8, "application/json")).Result;
    Console.WriteLine(response1.Content.ReadAsStringAsync().Result);
}

Which will output:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

{"d":"Hello World"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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