简体   繁体   中英

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.

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, eg. 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.

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.

如果要发送PUT ,请尝试使用Fiddler ,这将允许您使用任何HTTP方法构建请求,修改请求标头,查看响应标头等。对于测试WCF服务非常有用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM