在单个操作上启用多个HTTP方法?

我有一个操作合同(下面),我想允许GET和POST请求。 如何告诉WCF接受单个OperationContract的两种类型的请求?

[OperationContract, WebInvoke(Method="POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "query")] XElement Query(string qry); [OperationContract, WebInvoke(Method="GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "query?query={qry}")] XElement Query(string qry); 

如果有人在寻找不同的解决方案,

 [OperationContract] [WebInvoke(Method="*")] public <> DoWork() { var method = WebOperationContext.Current.IncomingRequest.Method; if (method == "POST") return DoPost(); else if (method == "GET") return DoGet(); throw new ArgumentException("Method is not supported."); } 

这篇由Carlos Figueira在MSDN论坛上发布的post有一个解决方案。 我现在就说这个,但如果有人有任何更清洁的解决方案,请告诉我。

 [OperationContract, WebInvoke(Method="POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "query")] XElement Query_Post(string qry); [OperationContract, WebInvoke(Method="GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "query?query={qry}")] XElement Query_Get(string qry); 

您可能想要查看WebGetAttribute,我自己没有尝试过,但您可以将它与WebInvokeAttribute一起应用于同一方法。

有关MSDN和Jeff Barnes的信息 。

对于上述问题,在Query_Get API的情况下将WebInvoke更改为WebGet将解决该问题。

但是,GET和POST意味着不同的行为。

这不会让客户感到困惑,从REST的角度来看是错的吗?

不使用WebInvoke就可以了。

不过,这可能不是您正在寻找的答案。