简体   繁体   中英

jQuery Ajax call returning null from WCF RIA REST service

I have created a WCF REST .NET 4 service and deployed it to a local IIS 7. If I use Fiddler and use the request builder, I am able to call the service and see the data been returned OK. If I try hitting the same REST location in the browser, JSON is not been returned but it looks like XML .

My service looks like this:

[OperationContract]
[WebGet(UriTemplate = "/{id}/details.json",
    ResponseFormat=WebMessageFormat.Json)]
public SampleItem Get(string id)
{
    return new SampleItem{ Id=1, StringValue="value from string"};
}

My web.config file has only a slight change:

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"/>

I am trying to call the service using jQuery like this:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "http://wcf-rest/service1/1/details.json",
        dataType: "json",
        success: function (data) { alert(data); },
        error: function (e) { alert("error"); }
    });
}); // end .ready

However, null is being returned every time. What do I need to change?

I've been using jQuery and Ajax extensively with a JSON datatype, and I believe you need to change data to data.d . See my example below.

function getMakes() {
    $.ajax({
        type: "POST",
        url: "../../WebService_VehicleAssignment.asmx/getAllVehicleMakes",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var response = msg.d;
            $('#output').empty();
            $.each(response, function (vehicle, vehicle) {
                $('#output').append(new Option(vehicle.Make, vehicle.Id));
            });
        },
        failure: function (msg) {
            alert('failure');
        }
    });
}<br />

I use Firebug to debug this stuff. I can see exactly what's getting posted to the web service and what is coming back. And if the web service is complaining, what it's complaining about.

Read about why the .d is necessary in A breaking change between versions of ASP.NET AJAX . In short, I believe it is a wrapper so that returned data is treated as a string rather than being returned and executed if it is raw literal JavaScript code.

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