从WCF/ADO.NET数据服务的请求主体接收参数
问题描述:
我试着发布到ADO.NET数据服务,但参数似乎迷路了。从WCF/ADO.NET数据服务的请求主体接收参数
我有一样的东西:
[WebInvoke(Method="POST")]
public int MyMethod(int foo, string bar) {...}
,我让使用prototype.js作为Ajax调用:
var args = {foo: 4, bar: "'test'"};
new Ajax.Requst(baseurl + 'MyMethod',
method: 'POST',
parameters: args,
onSuccess: jadda,
onFailure: jidda
}
如果我取代 “的方法: 'POST'” 用“的方法: 'GET'“和”WebInvoke(Method =“POST”)“与”WebGet“一切正常,但现在(使用后)我得到的是:
错误请求 - 查询语法错误。
从服务。
唯一的修复(我不想使用)是发送URL中的所有参数,即使我执行一个帖子。任何想法都欢迎。
答
当你指定参数时,WCF和ASMX web服务往往会对请求主体稍微有所选择,通常将请求编码为表单文章,即foo = 4 & bar = test而不是你需要指定javascript文字: -
new Ajax.Request(baseurl + 'MyMethod', {
method: 'POST',
postBody: '{"foo":4, "bar":"test"}',
encoding: "UTF-8",
contentType: "application/json;",
onSuccess: function(result) {
alert(result.responseJSON.d);
},
onFailure: function() {
alert("Error");
}
});
答
如果您想使用POST,则需要指定要包装在WebInvoke属性中的请求中的参数,除非参数包含在对象上(例如消息合约)。这是有道理的,因为如果没有包装在json或xml中,就无法序列化参数。
无包装这不是XML确实包装为缺少根元素
<foo>1</foo>
<bar>abc</bar>
,有效的XML
<Request>
<foo>1</foo>
<bar>abc</bar>
</Request>
此示例也适用于JSON
答
你是说我应该换行参数我的javascript像
var args = {Request: {foo: 3, bar: "'test'"}}
还是我错过了什么?
我试着添加:
ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped
到WebInvoke属性,但没有结果。我试图将“Content-Type”(在js POST ajax-call中)设置为“application/x-www-form-urlencoding”和“application/json; charset = utf-8”,但没有结果。