WCF Restful服务GET / POST

时间:2012-07-30 17:06:03

标签: c# wcf rest

我可以这样做吗?

[OperationContract]    
[WebInvoke
  (  
    Method = "POST",
    ResponseFormat = WebMessageFormat.Json,
    RequestFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "/abc{integerParam}"
  )
]
ResultStruct abc( int integerParam, CustomClass secondParam );

这里的想法是我可以在url中传递第一个参数(整数),但是secondParam来自POST。这甚至可能吗?

我从WCF REST开始,不确定如何分配参数。任何指针都会有所帮助,谢谢

1 个答案:

答案 0 :(得分:22)

是的,你可以,这里来自A Guide to Designing and Building RESTful Web Services

[ServiceContract]
public partial class BookmarkService
{
    [WebInvoke(Method = "PUT", UriTemplate = "users/{username}")]
    [OperationContract]
    void PutUserAccount(string username, User user) {...}

    [WebInvoke(Method = "DELETE", UriTemplate = "users/{username}")]
    [OperationContract]
    void DeleteUserAccount(string username) {...}

    [WebInvoke(Method = "POST", UriTemplate = "users/{username}/bookmarks")]
    [OperationContract]
    void PostBookmark(string username, Bookmark newValue) {...}

    [WebInvoke(Method = "PUT", UriTemplate = "users/{username}/bookmarks/{id")]
    [OperationContract]
    void PutBookmark(string username, string id, Bookmark bm) {...}

    [WebInvoke(Method = "DELETE", UriTemplate = "users/{username}/bookmarks/{id}")]
    [OperationContract]
    void DeleteBookmark(string username, string id) {...}
    ...
}

对我而言,这种设计RESTful Web服务非常糟糕。这个ServiceContrcat是:

  • 无法维护,脆弱的远程接口
  • 必须创建太多方法
  • 缺少多态性

我相信,远程接口应该稳定灵活,我们可以使用基于消息的方法来设计Web服务。

您可以在此处找到详细说明:Building RESTful Message Based Web Services with WCF,代码示例:Nelibur和Nelibur nuget package here