Web Service, in general, is just a reusable function that can be called from any program over HTTP.
Script to create Web Service in Visual Studio.
- [WebMethod]
- [ScriptMethod(UseHttpGet = true)]
- public int Add(int a, int b) {
- return (a + b);
- }
ScriptMethod is used for getting parameter's value through Query string and also, to use other AJAX request mechanism [mainly Get operation]. It helps in providing resopnse in XML formatted manner.
In order to use query string parameter, there are a few modifications needed in web.config file inside system.web tag.
- <webServices>
- <protocols>
- <add name="HttpGet" /> </protocols>
- </webServices>
Once it is setup, to test the Web Service using browser console itself, run the application by hitting F5 and open a page browser where jQuery is included. Click on F12 and navigate to console module and run the below code.
- $.ajax({
- url: "http://localhost:XXXXX/ArthimeticService.asmx/Add?a=6&b=8",
- datatype: "html",
- contentType: "text/plain",
- }).done(function(data) {
- var t = data.childNodes;
- console.log($(t).text())
- });
Both, dataType and contentType are not mandatory. These are used just to check different responses. We will get the response in the data object.
Note
Only after it is published, it will be available on internet, else it can be checked on localhost system only.