Web service and Script service

0

Most of you are familiar about writing a web service using c#. Visual Studio provides the project template which easily creates a web service for you.

Visual Studio Project Template

Hello world web service

I’m sure you may know how to call this web service using c#. But do you know how to call the web service using client side scripts such as JavaScript? There are various ways to do this. I will demonstrate this using jQuery$.ajax() function.

        function callSvc() {
            $.ajax({
                type: "POST",
                url: "Service1.asmx/HelloWorld",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data, status) { alert(data); },
                error: function(request, status, error) { alert(request); alert(status); alert(error); }
            });
        }
    

When you call the HelloWorld() service, by default you will get “500 – Internal server error” error message.

JavaScript debug mode

This error raised because you haven’t configured this service to access using client side scripts. When you Check the responseText, you will notice that it says “Only Web services with a [ScriptService] attribute on the class definition can be called from script.

To resolve this you have to configure your web service with [ScriptService] attribute.

[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService

When adding [ScriptService] attribute to the web service, it gets automatically handled by the ScriptHandlerFactory and creates a JavaScript proxy class for the web service. That means, you will be able to call the web service from the client side script same way as you call it from the code behind. You can view the generated proxy class by using the following command.

http://<URL>/SimpleWebService.asmx/js
http://<URL>/SimpleWebService.asmx/jsdebug

Compare the generated proxy class with the service description (http://<URL>/Service1.asmx?WSDL) and let me know what you noticed.

Download Demo Project