user903601
user903601

Reputation:

Getting POST or PUT to work in a WCF REST Service

I have a WCF Service and I am able to GET from it but I can’t work out how to PUT to it. I just want to increment a hits field each time the record is used in the client. Here is some of my code.

Interface:

[OperationContract]
[WebInvoke(Method = "PUT",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Wrapped,
    UriTemplate = "IncSMS")]
void IncSMS();

Method:

public void IncSMS()
{
    var business =
        (from p in _db.Businesses
            where p.BusinessID == 1
            select p).FirstOrDefault();
    business.SMSHits += 1;
    _db.SaveChanges();
}

I’m getting “Method not allowed.” In IE, can anyone see what I’m doing wrong???

Cheers,

Mike.

Upvotes: 5

Views: 7143

Answers (3)

user903601
user903601

Reputation:

Well, I asked the question and it took me three days to find the answer to something that should have been very simple.

So the question ended up being: How do I add a Content-Length header to my request???

Answer: You can’t add Content-Length to a URI when typed into a browser, “because by default it will perform a GET”!!! To add Content-Length to your header you must use a debugging tool, e.g.. Fiddler or build a form or some other type of client!

In fiddler you simply type Content-Length: 0 in the “Request Headers” section of the “Request Builder” and it will magically work! As seen near the bottom of this tutorial: http://blog.donnfelker.com/2008/12/04/how-to-rest-services-in-wcf-3-5-part-2-the-post/

Thanks guys,

Mike.

Upvotes: 7

Cheeso
Cheeso

Reputation: 192627

Method not allowed generally means that, on the client side, you are using an HTTP method that does not match what you've configured in the WCF code. In your case you've specified PUT as the HTTP Method for that WCF -exposed service method. It could be that you are using HTTP POST when your attribute says PUT.

If you use Fiddler, you will be able to see the request and response. If the problem is as I've described, then when you send a POST, the raw response will look like this:

HTTP/1.1 405 Method Not Allowed
Allow: PUT
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Thu, 10 Nov 2011 02:17:43 GMT

The "Allow" header in the response will tell you: Please use PUT.

Upvotes: 2

Jeff Ogata
Jeff Ogata

Reputation: 57823

If you want to send a PUT, try using Fiddler, which will let you build a request using any HTTP method, modify request headers, view response headers, etc. Very useful for testing WCF services.

Upvotes: 0

Related Questions