如何在WCF休息服务的PUT中读取URL Body?

时间:2015-10-08 11:07:45

标签: .net wcf json.net wcf-rest

我是WCF休息服务的新手。我正在尝试实现PUT方法,它将从客户端

获取JSON输入

将此视为我的网址:

     $(".Send_user_id").click(function() {
        var uid  = $(this).attr('data-id');
        console.log('id: ' + uid ); 
  }); 

我已实施以下代码

{"73":"456212c5-149c-4f04-a41d-47eeb8feee01","74":"4825c4be-2f58-4021-88b1-a5dcd17079b5"}

IN服务:

    [OperationContract]
    [WebInvoke(Method = "PUT", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/ListOfAlerts", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void CloseAlert(String alertIDsToClose);

我如何指定json数据在body中不可用于url。我的函数如何从Body.Am中读取正确的跟踪数据?

请建议我......

1 个答案:

答案 0 :(得分:1)

如果使用对象数组而不是逗号分隔的JSON项,那将非常简单。在CloseAlerts

中使用DataContract作为参数
[DataContract]
public class Alert
{
    [DataMember( Name = "Id",IsRequired = false)]
    public int Id { get; set; }

    [DataMember(Name = "Guid", IsRequired = false)]
    public Guid guid { get; set; }
}

现在方法签名将是:

    [OperationContract]
    [WebInvoke(Method = "PUT", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/ListOfAlerts", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string CloseAlert(Alert[] alertIDsToClose);

那就是它。以下是测试方法:

Alert[] alerts = new [] { 
    new Alert {Id =1, guid = Guid.NewGuid()}, 
    new Alert {Id =2, guid = Guid.NewGuid()}
};

// Serialize with Json.net to keep more generalized
var data = JsonConvert.SerializeObject(alerts, typeof(Alert[]), new JsonSerializerSettings());

WebClient webClient = new WebClient();       
webClient.Headers["Content-type"] = "application/json";            
webClient.Encoding = Encoding.UTF8;

webClient.UploadString(baseAddress + "/ListOfAlerts", "POST", data);