我是WCF休息服务的新手。我正在尝试实现PUT方法,它将从客户端获得JSON输入
把它当作我的url正文:
{"73":"456212c5-149c-4f04-a41d-47eeb8feee01","74":"4825c4be-2f58-4021-88b1-a5dcd17079b5"}
我已经实现了以下代码
[OperationContract]
[WebInvoke(Method = "PUT", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/ListOfAlerts", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void CloseAlert(String alertIDsToClose);
在服务:SCOM_ConnectionSettings();
Guid alertId = Guid.Empty;
//StreamReader streamReader = new StreamReader(alertIDsToClose);
//streamReader.
Dictionary<string, string> alertIDs = JsonConvert.DeserializeObject<Dictionary<string, string>>(alertIDsToClose);
#region test
//String str = WebOperationContext.Current.IncomingRequest.Accept.ToString();
//StreamReader reader = new StreamReader(alertIDs);
//String res = reader.ReadToEnd();
//NameValueCollection coll = HttpUtility.ParseQueryString(res);
//foreach(string alertID in alertIDs)
//{
#endregion
foreach (KeyValuePair<string, string> alertID in alertIDs)
{
alertId = new Guid(alertID.Value);
}
MonitoringAlert monitoringAlert = mgGroup.GetMonitoringAlert(alertId);
ReadOnlyCollection<MonitoringAlertResolutionState> alertStates = mgGroup.GetMonitoringAlertResolutionStates();
MonitoringAlertResolutionState closedState = null;
foreach (MonitoringAlertResolutionState thisState in alertStates)
{
if (thisState.Name == "Closed")
{
closedState = thisState;
}
}
if (monitoringAlert.ResolutionState != closedState.ResolutionState)
{
monitoringAlert.ResolutionState = closedState.ResolutionState;
string comment = "closing availability alert";
monitoringAlert.Update(comment);
}
}
我如何指定json数据在body中而不是在url中可用。我的函数如何从body中读取数据。我走对了吗?
如果您使用对象数组而不是逗号分隔的JSON项,则会非常简单。使用DataContract作为CloseAlerts
.
[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);