bzamfir
bzamfir

Reputation: 4886

WCF REST service POST method

I need to create a REST service with a POST method with 4 string parameters

I defined it as below:

[WebInvoke(UriTemplate = "/", Method = "POST", BodyStyle= WebMessageBodyStyle.WrappedRequest)]
public Stream ProcessPost(string p1, string p2, string p3, string p4)
{
    return Execute(p1, p2, p3, p4);
}

And I want to invoke it with code as follows:

        string result = null;
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        string paramz = string.Format("p1={0}&p2={1}&p3={2}&p4={3}", 
            HttpUtility.UrlEncode("str1"),
            HttpUtility.UrlEncode("str2"),
            HttpUtility.UrlEncode("str3"),
            HttpUtility.UrlEncode("str4")
            );

        // Encode the parameters as form data:
        byte[] formData =
            UTF8Encoding.UTF8.GetBytes(paramz);
        req.ContentLength = postData.Length;

        // Send the request:
        using (Stream post = req.GetRequestStream())
        {
            post.Write(formData, 0, formData.Length);
        }

        // Pick up the response:
        using (HttpWebResponse resp = req.GetResponse()
                                      as HttpWebResponse)
        {
            StreamReader reader =
                new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
        }

        return result;

However, the client code returns code 400: Bad request

What am I doing wrong?

Thank you

Upvotes: 1

Views: 3600

Answers (2)

Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

I'd say declare the parameters in UriTemplate like below

[OperationContract]
[WebInvoke(UriTemplate = "{p1}/{p2}/{p3}/{p4}", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string ProcessPost(string p1, string p2, string p3, string p4);

And use the below code to invoke,

string result = null; 
string uri = "http://localhost:8000/ServiceName.svc/1/2/3/4";

HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";

using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) 
   { 
       StreamReader reader = new StreamReader(resp.GetResponseStream()); 
       result = reader.ReadToEnd(); 
   }

It works fine for me. Hope this approach is helpful.

Upvotes: 1

Javi
Javi

Reputation: 510

I'd say that form-urleconded format is not supported. The RequestFormat property of the attribute WebInvoke is of type WebMessageFormat enum which only defines JSON and XML as valid formats.

http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webmessageformat.aspx

Upvotes: 1

Related Questions