Passing complex objects into a WCF Rest Service

后端 未结 2 1751
予麋鹿
予麋鹿 2020-12-01 02:33

I have an Operation Contract that accepts a complex object and I\'m calling the operation through jQuery. How do I pass in a complex type object like that using jQuery. Bel

相关标签:
2条回答
  • 2020-12-01 02:48

    See Denny's post for a start, although I don't agree with his use of GET, and passing JSON in the querystring for complex params. That seems really wrong.


    The param you use for data is the json representation of whatever your Resolution type is. For example, suppose the type and operation is defined like this on the server side:

    [DataContract( Namespace = "urn:brandon.michael.hunter/ws/2010/01", 
                   Name = "Resolution" )]
    public class Resolution
    {
        [DataMember( IsRequired = true, Name = "Name" )]
        public string Name     { get; set; } 
    
        [DataMember( IsRequired = true, Name = "Rank" )]
        public int Rank { get; set; }
    
        [DataMember( IsRequired = true, Name = "SerialNumber" )]
        public int SerialNumber { get; set; } 
    
        [DataMember( IsRequired = false, Name = "Id" )]
        public int Id { get; set; } 
    }
    
    [OperationContract]
    [WebInvoke(Method = "PUT",
               RequestFormat=WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json,
               UriTemplate = "new")]
    public Resolution CreateNewResolution(Resolution r)
    {
        // your logic here
        r.Id = System.Guid.NewGuid();
        return r;
    }
    

    Then, in Javascript, the code you use might look like this:

    var resolution = {r: { Name : "Fred", Rank : 2,  SerialNumber : 17268 }};
    
    // convert object to JSON string  (See http://jollytoad.googlepages.com/json.js)
    var objectAsJson = $.toJSON(resolution);
    // result is a string:  '{"Name":"Fred","Rank":"2","SerialNumber":"17268"}'
    
    $.ajax({
      type        : "PUT",              // must match Method in WebInvoke
      contentType : "application/json",
      url         : "Service.svc/new",  // must match UriTemplate in WebInvoke
      data        : objectAsJson, 
      dataFilter  : function (data, type) {
          // convert from "\/Date(nnnn)\/" to "new Date(nnnn)"
          return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1');
      },
      processData : false,              // do not convert outbound data to string (already done)
      success     : function(msg){ ... },
      error       : function(xhr, textStatus, errorThrown){ ... } 
     });
    

    Notes:

    • You need to have the name of the variable (r) to be the first object in the JSON that is being passed, at least with WCF 4. When I used the previous example, it did not work until I put in the name of the variable at the beginning.
    • For passing complex objects in JSON, use PUT or POST as the type (HTTP Method) of the request
    • you need to convert the complex object to a JSON string. There's a nice, tiny jquery plugin to do this. Denny provides his own implementation.
    • I found that if I use processData=true, then the resulting string sent to the service is in querystring format, not in JSON. Not what I want for passing complex objects. So I set it to false. Using true would be fine for simpler non-JSON requests where you're doing WebGet, and all the params are in the query string.
    • the dataFilter allows for correct deserialization of DateTime objects
    • the msg param passed to the success callback contains the returned json.
    • You may want to use a URL rewriter to hide that .svc tag in the request URL
    • in this case, the WCF service uses the webHttp behavior, not enableWebScript. The latter dynamically generates Javascript proxies to invoke the service, but the way you asked the question, makes it seem like you don't want that.

    0 讨论(0)
  • 2020-12-01 03:04

    Check out Gil Fink's blog regarding Combining WCF Data Services, JSONP and jQuery

    http://blogs.microsoft.co.il/blogs/gilf/archive/2011/04/24/combining-wcf-data-services-jsonp-and-jquery.aspx

    During Mike Flasko’s session at MIX11, he showed how to create a JSONP aware WCF Data Service with a JSONPSupportBehavior attribute that is available for download from MSDN code gallery (and is supposed to be a part of Microsoft.Data.Services.Extensions namespace). In this post I’ll show a simple example that uses the attribute and jQuery in order to make a JSONP cross domain call for a WCF Data Service.

    Setting up the Environment

    First I started by creating two different ASP.NET web applications. The first application includes the calling page and the second includes the WCF Data Service. Then, I created in the second web application an Entity Framework model and the WCF Data Service from that model. I also added the JSONPSupportBehavior.cs class that exists in the link I supplied earlier. The class includes the implementation of JSONPSupportBehavior which implements the WCF IDispatchMessageInspector interface. Also it includes the JSONPSupportBehaviorAttribute which I use in my code. The code is simple and looks like:

    [JSONPSupportBehavior] 
    public class SchoolDataService : DataService<SchoolEntities>
    {
      // This method is called only once to initialize service-wide policies.
      public static void InitializeService(DataServiceConfiguration config)
      {      
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);      
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
      }
    }
    

    Making the JSONP Call

    In the second web application I’ve created a web form that will hold the JSONP call example. Here is the code that makes the call:

    <!DOCTYPE html>
    <html>
    <head runat="server">
        <title>JSONP Call</title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="form1" runat="server">
        <output id="result">
        </output>
        </form>
        <script type="text/javascript">
            $.getJSON('http://localhost:23330/SchoolDataService.svc/Courses?$format=json&$callback=?', 
            function (response) { 
                $.each(response.d, function (index, value) {
                    var div = document.createElement('div');
                    div.innerHTML = value.Title;
                    $('#result').append(div);
                })
            });        
        </script>
    </body>
    </html>
    

    Lets explore the web form code: At first I use Microsoft CDN in order to retrieve the jQuery library. Then, I’ve created a HTML5 output element in order to append to it the output of the call. In the main script I use jQuery’s getJSON function which is calling the WCF Data Service. Pay attention that in order to get a JSON response from the WCF Data Service you need to use the $format=json query string parameter. After I retrieve the data I iterate and create a div element for each course title that was retrieved. This is done in the success function that I wired in the getJSON function call. Here is the output of running the code:

    enter image description here

    Summary

    In the post I supplied a simple example of making a JSONP call to a WCF Data Service using jQuery. This sort of solution can help you to consume WCF Data Services that exists in other domains from your client side. In a follow up post I’ll show the same example using the new datajs library

    0 讨论(0)
提交回复
热议问题