将复杂对象传递到 WCF 休息服务中 [英] Passing complex objects into a WCF Rest Service

查看:27
本文介绍了将复杂对象传递到 WCF 休息服务中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受复杂对象的操作合同,我正在通过 jQuery 调用该操作.如何使用 jQuery 传递像这样的复杂类型对象.以下是操作签名:

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. Below is the operation signature:

public Resolution CreateNewResolution(Resolution NewResolution);

我需要在客户端传递一个Resolution对象,但我不知道如何使用jQuery.有什么帮助吗?

I need to pass in a Resolution object on the client, but I don't know how to do something like using jQuery. Any help?

谢谢

推荐答案

参见 Denny 的帖子 作为开始,尽管我不同意他使用 GET,并在查询字符串中为复杂参数传递 JSON.这似乎是错误的.

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.

您用于 data 的参数是任何分辨率类型的 json 表示.例如,假设类型和操作在服务器端是这样定义的:

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;
}

然后,在 Javascript 中,您使用的代码可能如下所示:

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:

  • 您需要将变量 (r) 的名称设为要传递的 JSON 中的第一个对象,至少在 WCF 4 中是这样.当我使用前面的示例时,直到我放入开头的变量名.
  • 为了在 JSON 中传递复杂的对象,使用 PUT 或 POST 作为请求的类型(HTTP 方法)
  • 您需要将复杂对象转换为 JSON 字符串.有 一个不错的小型 jquery 插件可以做到这一点.丹尼提供了他自己的实现.
  • 我发现如果我使用 processData=true,那么发送到服务的结果字符串是查询字符串格式,而不是 JSON.不是我想要传递复杂对象的东西.所以我把它设置为false.对于正在执行 WebGet 且所有参数都在查询字符串中的更简单的非 JSON 请求,使用 true 会很好.
  • dataFilter 允许正确反序列化 DateTime 对象
  • 传递给成功回调的 msg 参数包含返回的 json.
  • 您可能希望使用 URL 重写器来隐藏请求 URL 中的 .svc 标记
  • 在这种情况下,WCF 服务使用 webHttp 行为,而不是 enableWebScript.后者动态生成 Javascript 代理来调用服务,但是您提出问题的方式使您似乎不想要那样.
  • 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.

这篇关于将复杂对象传递到 WCF 休息服务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆