简体   繁体   中英

How to structure a server-side datasource that returns JSON objects?

I'm currently new into client-side programming, especially using the Jquery Ajax method to call server-side methods.

Until now I've used a System.Web.Services.WebService to host multiple methods to return a String or a bool. This approach has the advantage, that I can "group" methods with a similar purpose, like "methods for a comment-system". A disadvantage, as I've read many times, is that *.asmx services are outdated and the Json support isn't that well.

I've always read that a good way to provide methods that return JSON objects is the use of generic handlers (*.ashx). Generic handlers that I've written in the past provided only one single "action" per handler. Is using generic handlers for a JSON datasource the way to go? I clearly see the disadvantage of not being able to "group" methods, because each method would be in a seperate .ashx.cs file. (I know that I could pass a second argument that determines which "action" should be called, but somehow doesn't feel right).

Using a WCF service is not a worthwhile option at the moment, because the methods that I use need access to the session and adjusting a service to fit the same purpose is just an overkill for now.

I guess the real question is: What is a modern way to return JSON objects / List of JSON objects while maintaining readability / structure of the service-side methods?

Edit : I'm using Webforms 4.0

I'd stick with WebServices I've never had problems with the JSON being returned from them. using ajax with jQuery is simple also

    $.ajax({
        type: "POST",
        url: "/Methods/Zipcodes.asmx/GetPOIMarkersFrontendByTypeAndZip",
        data: "{latlng: '" + lat + "," + lng + "', type: '" + type + "', distance: '" + distance + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(html) {
        }
    }

is a brief example of passing data to a webservice

    [WebMethod]
    public object GetPOIMarkersFrontendByTypeAndZip(string latlng, string type, string distance)
    {
        var db = new SQLConnectionDataContext();

        string[] zip = latlng.Split(',');
        IQueryable<POI> points = db.POIs;
        int dist = string.IsNullOrEmpty(distance) ? 0 : Convert.ToInt32(distance);

        List<POI> poi = type == "0"
                            ? points.ToList()
                            : points.Where(p => p.poiTypeId == Convert.ToInt32(type)).ToList();

        return (from item in poi
                where !string.IsNullOrEmpty(item.Lat) && !string.IsNullOrEmpty(item.Lng)
                let dDist =
                    DoCalc(Convert.ToDouble(zip[0]), Convert.ToDouble(item.Lat.Trim()), Convert.ToDouble(zip[1]),
                           Convert.ToDouble(item.Lng.Trim()))
                where dDist <= dist
                select new GoogleMapMarker
                           {
                               lat = item.Lat,
                               lng = item.Lng,
                               data = FpsFunctions.IsLanguageFrench() ? item.fr : item.gb,
                               tag = item.poiTypeId.ToString()
                           }).ToList();
    }

this would return a JSON array with 4 variables for me to use. Not once had problems and also it allows for you to populate html sites with data on the fly like ASP.NET allows. Just getting you're head round jQuery :)

I have moved onto MVC, which makes this sort of thing a lot easier. But when I did this in WebForms, I would use one or more handlers (ASHX) that took in an action parameter. The action parameter would then be evaluated against to call the appropriate target method which would handle the response.

If you go this route, you're saving yourself the headache of all those files. And what you lose in having to specify an action parameter on your ajax calls, you gain in not having to specify different file names.

I would suggest looking at Web API

http://www.asp.net/web-api

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM