您的操作需要一个字符串作为rIds
参数,但您将一个数组传递给它。有一些转换是自动发生的,但只有非常简单的转换(例如数字到字符串)。此外, rScope 需要一个字符串,但您正在将一个对象传递给它。
您可以做几件事。第一种是将数据作为字符串而不是作为它们的“正常”类型传递——这意味着对RIds
和rScope
参数进行字符串化:
var data = JSON.stringify({
Id: Id,
rIds: JSON.stringify(RIds),
rScope: JSON.stringify(rScope)
});
$.ajax({
url: "/Web/WebServices/Operation.svc/SetScope",
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () { },
dataType: "json",
cache: false,
data: data,
success: function (data) { onSuccess(data); },
error: function (data) { onError(data); }
});
另一种选择与 François Wahl 提到的一致,即制作将接收您发送的数据的类型。您需要为rIds
和rScope
参数执行此操作:
public class StackOverflow_13575100
{
[ServiceContract]
public class Service
{
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
public string SetScope(int rId, string rIds, string rScope)
{
return string.Format("{0} - {1} - {2}", rId, rIds, rScope);
}
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public string SetScopeTyped(int rId, int[] rIds, ScopeClass[] rScope)
{
return string.Format("{0} - {1} - {2}",
rId,
"[" + string.Join(", ", rIds) + "]",
"[" + string.Join(", ", rScope.Select(s => s.ToString())) + "]");
}
}
[DataContract]
public class ScopeClass
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
public override string ToString()
{
return string.Format("Scope[Id={0},Type={1}]", Id, Type);
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
c.Headers[HttpRequestHeader.ContentType] = "application/json";
string data = @"{""Id"":1,""rIds"":[1,2,3,4],""rScope"":[{""id"":3,""type"":""barney""},{""id"":2,""type"":""ted""}]}";
Console.WriteLine(data);
try
{
Console.WriteLine(c.UploadString(baseAddress + "/SetScope", data));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
c.Headers[HttpRequestHeader.ContentType] = "application/json";
Console.WriteLine(c.UploadString(baseAddress + "/SetScopeTyped", data));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}