Thursday, March 31, 2011

Enable multiple HTTP Methods on a single operation?

I have an operation contract (below) that I want to allow GET and POST requests against. How can I tell WCF to accept both types of requests for a single 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);
From stackoverflow
  • Not using WebInvoke will do the trick.

    That may not be the answer you're looking for, though.

    spoon16 : What do you mean not using webinvoke will do the trick?
  • This post over on the MSDN Forums by Carlos Figueira has a solution. I'll go with this for now but if anyone else has any cleaner solutions let me know.

    [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);
    
  • You may want to take a look at the WebGetAttribute, I have not tried it myself but you may be able to apply it to the same method along with the WebInvokeAttribute.

    Info on MSDN, and Jeff Barnes.

    spoon16 : There is no difference between WebInvoke(Method = "GET") and WebGet()
  • For the issue described above, changing the WebInvoke to WebGet in the case of Query_Get API will solve the issue.

    spoon16 : There is no difference between WebInvoke(Method = "GET") and WebGet()
  • GET and POST imply different actions though.

    Won't this be confusing for clients, and wrong from a REST perspective?

    spoon16 : I'm coding the endpoint based on a specification from the W3C. That specification describes one method that supports multiple operations (GET and POST). If the query is to large for a GET request (URL length) the consumer can use POST.

0 comments:

Post a Comment