【问题标题】:Receive parameter from request body in WCF/ADO.NET Data Service从 WCF/ADO.NET 数据服务中的请求正文接收参数
【发布时间】:2008-10-22 10:17:37
【问题描述】:

我正在尝试发布到 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
}

如果我将“method: 'POST'” 替换为“method: 'GET'” 并将“WebInvoke(Method="POST")” 替换为“WebGet” 一切正常,但现在(使用 post)我得到的只是:

错误请求 - 查询语法错误。

来自服务。

唯一的解决方法(我不想使用)是发送 URL 中的所有参数,即使在我执行发布时也是如此。欢迎任何想法。

【问题讨论】:

    标签: .net javascript ajax wcf ado.net


    【解决方案1】:

    WCF 和 ASMX 网络服务往往对请求正文有点挑剔,当您指定 args 时,请求通常被编码为表单帖子,即 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");
            }
        });
    

    【讨论】:

      【解决方案2】:

      如果要使用 POST,则需要在 WebInvoke 属性中指定要包装在请求中的参数,除非参数包含对象(例如消息合约)。这是有道理的,因为如果不包装在 json 或 xml 中,就无法序列化参数。

      未包装的确实不是 XML,因为缺少根元素

      <foo>1</foo>
      <bar>abc</bar>
      

      已包装的有效 XML

      <Request>
         <foo>1</foo>
         <bar>abc</bar>
      </Request>
      

      此示例也适用于 JSON

      【讨论】:

        【解决方案3】:

        你是说我应该像javascript一样包装参数

        var args = {Request: {foo: 3, bar: "'test'"}}
        

        还是我错过了什么?

        我已经尝试添加:

        ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped
        

        到 WebInvoke-attribute 但没有结果。我尝试将“Content-Type”(在 js POST ajax-call 中)设置为“application/x-www-form-urlencoding”和“application/json; charset=utf-8”,但没有结果。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多