【问题标题】:Wcf service RESTfulWcf 服务 RESTful
【发布时间】:2011-12-23 16:00:21
【问题描述】:

我用这样的帖子做了我的方法:

[OperationContract]
[WebInvoke(Method = "POST",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Bare)]
List<Human> GetHuman(UserEnteredName humanName);

UserEnteredName 类只有一个属性 - 字符串。

而且它有效。但是,我需要让它被获取,而不是发布。

我试过这个:

[WebInvoke(Method= "GET", UriTemplate = "GetHuman?username={John}", 
           ResponseFormat = WebMessageFormat.Json, 
           RequestFormat = WebMessageFormat.Json)]

但它不起作用。我需要改变什么?

【问题讨论】:

  • 发布错误..“不起作用”是什么意思?
  • @andreapier 错误是 500 内部服务器错误。
  • 也许您正试图从一个不是基础域的域中获取一些 json?即:您的基本域是 www.mydomain.com 并且您正在从 inner.mydomain.com 进行 ajax 调用?
  • @andreapier 我尝试使用 UriTemplate = "Service1.svc/json/GetHuman?custName=John",仍然没有结果。
  • 我只是想知道您是否试图违反同源政策。在这种情况下,您需要使用 jsonP 而不是经典 json。让我知道。顺便说一句,漂移是正确的,之前尝试一下

标签: wcf json post get


【解决方案1】:

根据您的UriTemplate,您的方法必须类似于

Human GetHuman(string John)

我怀疑您错误地将可能的参数值放入您的UriTemplate。尝试类似

[WebInvoke(Method= "GET", UriTemplate = "GetHuman?username={userName}", 
           ResponseFormat = WebMessageFormat.Json, 
           RequestFormat = WebMessageFormat.Json)]
Human GetHuman(string userName)

另外,对于GET,你可以使用WebGetAttribute,它稍微干净一些。


我会将您的方法更改为采用string 参数并在方法主体中构造UserEnteredName 实例。如果您的UserEnteredName 类型使用TypeConverterAttribute,则可以将其用作参数,但我从未这样做过,所以我不能说它有多容易(或不简单)。请参阅 WCF Web HTTP Programming Model Overview,特别是 UriTemplate 查询字符串参数和 URL 部分。

【讨论】:

  • 我试过了,但没用 我的方法如下所示: List GetHuman(UserEnteredName humanName);但 UserEnteredName 是一个包含字符串属性 userName 的类
  • 我很惊讶你甚至可以让它编译......你怎么能传递一个字符串而不是一个 UserEnteredName?也许你为我们写了一个简化的例子?或者,也许您可​​以尝试为您的 GetHuman 方法使用一个将字符串作为输入参数的包装器
  • @andreapier 我更新了我的问题 - 关于 UserEnteredName 类。
猜你喜欢
  • 1970-01-01
  • 2016-01-11
  • 2011-03-23
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多