Asp.Net Web Service - Return String Response instead of XML

← Prev

In this article I am going to show you how to configure an Asp.Net web service to return a string response instead of xml.

The Web Service (C#)

This is my web service. The WebMethod "HelloWorld", when called using Ajax, returns a value. However the value is "serialized" to XML and the web serivice will return the value in XML format. This is the default behaviour.

In this case, I need to configure (or tell my web service) to use JSON as default response format.

using System;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

• First, you'll have to add "System.Web.Script.Services" namespace. It provides attributes that allow you to customise web service support for Ajax in Asp.Net.

• Second, add the attribute "[ScriptMethod(ResponseFormat = ResponseFormat.Json)]" to the WebMethod. This will make sure that the response (the value that it will return) is in JSON format.

Web Service (VB)

Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Services

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function
End Class

Call Web Service using Ajax in jQuery

While sending an Ajax request, make sure the contentType is set to 'application/json; charset=utf-8' and dataType is 'json'.

$.ajax({
    type: 'POST',
    url: 'WebService.asmx/HelloWorld',
    data: "",
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json'
    success: function (response) {
        alert (response.d);
    }, error: function (error) { console.log(error.responseText); }
});

← Previous