How to force requests to be JSON? I.e. how to bloc

2019-08-24 12:03发布

问题:

I have a REST WCF service and a WCF client application for it.

My operation has the WebGet attribute with the following properties: BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json

However, when I use the WCF client, the request is made with the body in XML format! This is undesirable! How can I change it to use JSON?

Furthermore, I want to prevent XML from being accepted on the server side, as well - how can I accomplish this? I would have expected specifying RequestFormat to do it but it appears to be just a suggestion?

Edit: nevermind, I am an idiot. I was looking at the wrong operation contract - the right ones were inside a #region that I had not expanded... the client works fine. The server point is still valid but in the context of this question, it's probably for the better to consider this question closed.

回答1:

What do you mean you are specifying [WebGet] and getting an request with an XML body? A GET request can't have a body (any inputs must be part of the URL path or the query string). Are you talking about [WebInvoke]?

As for enforcing the request format on the server side, right now, I think WCF by default just handles both formats regardless of what you specified on the contract. You can probably enforce it yourself by looking at the request message content type and rejecting it if it's "text/xml" (or anything other than application/json for that matter).



回答2:

Nevermind, I am an idiot. I was looking at the wrong operation contract - the right ones were inside a #region that I had not expanded... the client works fine. The server point is still valid but in the context of this question, it's probably for the better to consider this question closed.



标签: wcf json rest