为什么我不能在WCF REST POST方法中使用两个参数呢

本文关键字:参数 两个 不能 WCF REST 方法 POST 为什么 | 更新日期: 2023-09-27 17:59:28

我有合同:

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, UriTemplate = "GetCategoriesGET/{userIdArg}", BodyStyle = WebMessageBodyStyle.Bare)]
    List<Video> GetVideosGET(string userIdArg);
    [WebInvoke(Method = "POST", UriTemplate = "evals")]
    [OperationContract]
    void SubmitVideoPOST(Video videoArg, string userId);

我有实现方法:

public List<Video> GetVideosGET(string userIdArg)
{
  List<Video> catsToReturn = new List<Video>();
  if (Int32.Parse(userIdArg) == 1)
  {
      catsToReturn = catsForUser1;
  }
  else if (Int32.Parse(userIdArg) == 2)
  {
      catsToReturn = catsForUser2;
  }
  return catsToReturn;
  }

  public void SubmitVideoPOST(Video videoArg, string userId)
  {
  }

当我浏览到:

http://localhost:52587/Api/Content/VLSContentService.svc/GetCategoriesGET/1

我收到这个错误:

"/"应用程序中的服务器错误。的操作"SubmitVideoPOST"合同"IVL内容服务"指定多个请求主体要序列化的参数任何包装器元素。最多一个身体参数可以在没有包装器元素。要么删除额外的身体参数或设置上的BodyStyle属性WebGetAttribute/WebInvokeAttribute到包装好了。

当我添加POST的新方法(我还没有尝试访问)时,我才在Get请求中开始出现这个错误,这意味着什么?我不能用不止一个论点吗?

为什么我不能在WCF REST POST方法中使用两个参数呢

看看这个链接,海报问了同样的问题。

相关部分是:

WCF doesn't support more than one parameter with bare body, 
if you need pass several parameters in one post method operation, 
then we need set the BodyStyle to Wrapped.

因此,在您的情况下,您必须将您的运营合同更改为以下内容:

[WebInvoke(Method = "POST", UriTemplate = "evals", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
[OperationContract]
void SubmitVideoPOST(Video videoArg, string userId);

XML不会有一个带有两个参数的根节点,这会使其格式不正确。要引入一个根节点,就必须按照错误所说的那样"包装"它

Add BodyStyle=WebMessageBodyStyle。包装到WebInvoke属性

您是否尝试将WebGetAttribute/WebInvokeAttribute上的BodyStyle属性设置为Wrapped,就像建议的错误一样,如下所示:

[WebInvoke(Method = "POST", UriTemplate = "evals", BodyStyle = WebMessageBodyStyle.Wrapped)]
[OperationContract]
void SubmitVideoPOST(Video videoArg, string userId);

我自己对WCF REST有些陌生,上周刚刚完成了我的第一项服务。但我也有类似的问题。这篇文章使我朝着正确的方向前进。包装纸是我的问题。