一段时间以来,我所有的ServiceStack服务都使用POST
动词来用于客户发送的传入请求。但是,在这种特殊情况下,我想使用GET
动词,并且我希望能够传递一个相当复杂的对象(例如,包含数组。)
这是我的ServiceStack代码:
[Route("Test")]
public class TestRequest : IReturn<TestResponse>
{
public Criteria Criteria { get; set; }
}
public class Criteria
{
public string Msg { get; set; }
public string[] Keys { get; set; }
}
[DataContract]
public class TestResponse
{
[DataMember]
public string Text { get; set; }
[DataMember]
public ResponseStatus ResponseStatus { get; set; }
}
public class TestService : ServiceInterface.Service, IGet<TestRequest>, IPost<TestRequest>
{
public object Get(TestRequest request)
{
return HandleRequest(request);
}
public object Post(TestRequest request)
{
return HandleRequest(request);
}
private object HandleRequest(TestRequest request)
{
if (request == null) throw new ArgumentNullException("request");
if (request.Criteria == null)
throw new ArgumentException("Criteria is null.");
return new TestResponse
{
Text =
String.Format(
"Text: {0}. Keys: {1}",
request.Criteria.Msg,
String.Join(", ", request.Criteria.Keys ?? new string[0]))
};
}
}
由HTML应用程序使用的,具有以下jQuery代码:
$(document).ready(function () {
$.when($.ajax({
url: '/Test',
type: 'get',
dataType: 'json',
contentType: 'application/json',
data: {
"criteria": JSON.stringify({
"msg": "some message",
"keys": ["key1", "key2"]
})
}
}).done(function (response) {
console.log(response);
}).fail(function (response) {
console.log(response);
}));
});
我的标准对象会创建,但Msg
和Keys
属性为null。
在以下POST
示例中,该应用程序按预期运行:
$(document).ready(function () {
$.when($.ajax({
url: '/Test',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
"criteria": {
"msg": "some message",
"keys": ["key1", "key2"]
}
})
}).done(function (response) {
console.log(response);
}).fail(function (response) {
console.log(response);
}));
});
我误会了什么?
注意:您不能将JSON字符串与JSON对象进行混合并匹配(即,在C#中输入POCO)。
您正在尝试发送一个序列化的JSON字符串,例如:
"{"msg":..."
在电线上进入一个期望json对象的poco,例如:
{"msg":...
如果标准是字符串,例如:
public class TestRequest : IReturn<TestResponse>
{
public string Criteria { get; set; }
}
它应该起作用,否则您需要更改JSON请求以发送JSON对象,而不是序列化的JSON对象 逃脱到JSON字符串中。
当您使用json.stringify与get请求时,查询字符串的形式不佳...