7

I've created a simple C# asp.net web service function which returns a string message
and I am calling it from page using jquery ajax.

C#:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
    return DateTime.Now.ToString();
}


JS:

    $(document).ready(function() {
    //alert("ready");
        $.ajax({
            type: "POST",
            contentType: "application/json; chatset=utf-8",
            url: "WebService2.asmx/HelloWorld",
            data: "{}",
            dataType: "json",
            success: function(msg) {
                //alert(msg); //doesnt works
                alert(msg.d);
            }
        });
    });

My question is that why does alert(msg); doesnt works

Reporter
  • 3,897
  • 5
  • 33
  • 47
Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98

2 Answers2

12

It's a security hardening mechanism.

Essentially, it helps protecting against CSRF type of attacks where the attacker reads a JavaScript array (downloaded as Json) from a victim website. They can do that by overriding JavaScript's Array type. d causes the returned Json to not be an array and thus turns Array overriding useless for the attacker.

See this great blog post: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

Ofer Zelig
  • 17,068
  • 9
  • 59
  • 93
  • +1 thanks, This means that only for "Array overriding" issue MS developers have added the {d:""} variable – Nitin Sawant Aug 29 '11 at 10:36
  • 2
    not at all nithin. read his answer carefully. "cross site request forgery attack" there is also a way to simulate XSS attack using this vulnerability. – naveen Aug 29 '11 at 11:04
8

ASP.NET and WCF JSON service endpoints actually wrap their JSON in an object with the “d” property to circumvent a subtle potential security flaw when using JSON

Phil Haack's post on this: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

This was introduced from ASP.NET3.5. If you want msg to work in both frameworks before and after 3.5, just try this small hack.

var data = msg.hasOwnProperty("d") ? msg.d : msg;

Courtesy Dave Ward: Never worry about ASP.NET AJAX’s .d again

naveen
  • 53,448
  • 46
  • 161
  • 251