操作はrIds
パラメーターの文字列を想定していますが、配列を渡しています。自動的に行われる変換がいくつかありますが、非常に単純なもの (数値から文字列への変換など) のみです。また、rScope は文字列を想定していますが、オブジェクトを渡しています。
できることがいくつかあります。1 つ目は、データを「通常の」型ではなく文字列として渡すことです。これは、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();
}
}