JSON WebService in ASP.NET

2020-07-29 01:58发布

问题:

How do I create an ASP.NET web service that returns JSON formatted data?

回答1:

The most important thing to understand is to know how to represent data in JSON format. Please refer http://www.json.org/ to know more about it.

Once you understand this, then the rest part is pretty straight forward.

Please check the following URL for an example of the same.

http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=264 http://code.msdn.microsoft.com/JSONSampleDotNet
http://www.phdcc.com/xml2json.htm

I recommend Jquery library for this. It's a lightweight rich library which supports calling web services, handle json data format output etc.

Refer www.jquery.com for more info.



回答2:

.NET 3.5 has support built-in. For .NET 2.0, extra libraries are needed. I used the Jayrock library.

I recently delivered an application that uses pure Javascript at the browser (viz. using AJAX technology, but not using Microsoft AJAX or Scriptaculous etc) which marries up to Microsoft webservices at the back end. When I started writing this I was new to the world of .NET, and felt overwhelmed by all the frameworks out there! So I had an urge to use a collection of small libraries rather than very large frameworks.

At the javascript application, I call a web service like this. It directly reads the output of the web service, cuts away the non JSON sections, then uses https://github.com/douglascrockford/JSON-js/blob/master/json2.js to parse the JSON object.

This is not a standard approach, but is quite simple to understand, and may be of value to you, either to use or just to learn about webservices and JSON.

// enclosing html page has loaded this:
<script type="text/javascript" src="res/js/json2.js"></script> 

// Invoke like this:
// var validObj = = callAnyWebservice("WebServiceName", "");
//    if (!validObj || validObj.returnCode != 0) {
//      alert("Document number " + DocId + " is not in the vPage database. Cannot continue.");
//      DocId = null;
//    }


function callAnyWebservice(webserviceName, params) {
  var base = document.location.href;
  if (base.indexOf(globals.testingIPaddr) < 0) return;

  gDocPagesObject=null;

  var http = new XMLHttpRequest();
  var url = "http://mywebserver/appdir/WebServices.asmx/" + webserviceName;

  //alert(url + " " + params);

  http.open("POST", url, false);
  http.setRequestHeader("Host", globals.testingIPaddr);
  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  http.setRequestHeader("Content-Length", params.length);
  // http.setRequestHeader("Connection", "close");
  //Call a function when the state changes.
  http.onreadystatechange = function() { 
    if (http.readyState == 4 ) {
      if (http.status == 200) {

        var JSON_text = http.responseText;

        var firstCurlyQuote = JSON_text.indexOf('{');
        JSON_text = JSON_text.substr(firstCurlyQuote);
        var lastCurlyQuote = JSON_text.lastIndexOf('}') + 1;
        JSON_text = JSON_text.substr(0, lastCurlyQuote);   

        if (JSON_text!="")
        {
            //if (DEBUG)
            //  alert(url+" " +JSON_text);
            gDocPagesObject = eval("(" + JSON_text + ")");
        }
      }
      else if (http.readyState == 4)
        {alert(http.readyState + " " + http.status + " " + http.responseText)}
    }
  }

  http.send(params);

  if (gDocPagesObject != null) {
    //alert(gDocPagesObject.returnCode + " " + gDocPagesObject.returnString);
    return gDocPagesObject;
  }
  else
    return "web service unavailable: data not ready"; 
}


回答3:

In our project the requirements were as follow -- ASP.NET 2.0 on the server, and pure Javascript on the browser (no JQuery libs, or .NET AJAX)

In that case on the server side, just mark the webmethod to use JSON. Note that both input and output params are json formatted

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String Foo(String p1, String p2)
{
    return "Result: p1= " + p1 + " p2= " + p2;
}

On the javascript side, use the regular XmlHttpRequest object, make sure you format your input params as JSON and do an 'eval' on output parms.

var httpobj = getXmlHttpRequestObject();

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() 
{
    if (window.XMLHttpRequest) 
       return new XMLHttpRequest();
    else if(window.ActiveXObject) 
       return new ActiveXObject("Microsoft.XMLHTTP");
} 


CallService()
{
    //Set the JSON formatted input params
    var param = "{'p1' : 'value1', 'p2' : 'value2'}";

    //Send it to webservice
    if(httpobj.readyState == 4 || httpobj.readyState == 0)
    {
        httpobj.open("POST", 'service.asmx/' + 'Foo', true);
        //Mark the request as JSON and UTF-8
        httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');
        httpobj.onreadystatechange = OnSuccess;
        httpobj.send(param);
    }

}

OnSuccess()
{
   if (httpobj.readyState == 4) 
   {
      //Retrieve the JSON return param
      var response = eval("(" + httpobj.responseText + ")");
   }
}