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"}