Returning JSON from WCF Web API - wcf-web-api

The WCF Web API returns data either XML or JSON based on the Accept parameter in the request header not considering whether we set ResponseFormat=WebMessageFormat.Json in the WebInvoke/WebGet attributes. Is this the correct behavior of the API or a bug?

WCF Web API ignores the ResponseFormat attribute. That attribute is just there because of an effort to be backward compatible with previous WCF REST efforts.
The returned media type is based largely on the Accept header sent by the client.

Related

WCF Data Services version 5.0 and Json

I want my OData service to support Json serialization, I read about a WCF Data Service toolkit which add this behaviour to the V2 version. After I read WCF Data Service released a new version of WCF Data Service 5.0, I need to know how to do it.
I add the $Format=json and I get all the time this attribute isn't supported.
Any suggestion .
Thanks in advance ...
The usual way to request JSON is to use Accept header (basically following HTTP, if the client wants a certain representation of the response, it should ask for it in the Accept header).
So if you send Accept: application/json;odata=verbose, you will get the Verbose JSON response.
WCF Data Services currently doesn't implement the $format query option. But you can add it "on top". There are several ways to do this (just search the web). One of them is for example here: http://archive.msdn.microsoft.com/DataServicesJSONP

Implementing versioning a RESTful API with WCF or ASP.Net Web Api

Assume i've read a lot about versioning a restful api, and I decided to not version the the service through the uri, but using mediatypes (format and schema in the request accept header):
What would be the best way to implement a wcf service or a web api service to serve requests defining the requested resource in the uri, the format (eg. application/json) and the schema/version (eg player-v2) in the accept header?
WCF allows me to route based on the uri, but not based on headers. So I cannot route properly.
Web Api allows me to define custom mediatypeformatters, routing for the requested format, but not the schema (eg. return type PlayerV1 or PlayerV2).
I would like to implement a service(either with WCF or Web Api) which, for this request (Pseudo code):
api.myservice.com/players/123 Accept format=application/json; schema=player-v1
returns a PlayerV1 entity, in json format
and for this request:
api.myservice.com/players/123 Accept format=application/json; schema=player-v2
returns a PlayerV2 entity, in json format.
Any tips on how to implement this?
EDIT: To clarify why I want to use content negotiation to deal with versions, see here: REST API Design: Put the “Type” in “Content-Type”.
What you are bringing here does not look to me as versioning but it is is more of content negotiation. Accept header expresses wishes of the client on the format of the resource. Server should grant the wishes or return 406. So if we need more of a concept of Contract (although Web API unline RPC does not define one) then using resource is more solid.
The best practices for versioning have yet to be discussed fully but most REST enthusiast believe using the version in the URL is the way to go (e.g. http://server/api/1.0.3/...). This also makes more sense to me since in your approach using content negotiation server has to keep backward compatibility and I can only imagine the code at the server will get more and more complex. With using URL approach, you can make a clean break: old clients can happily use previous while new clients can enjoy the benefits of new API.
UPDATE
OK, now the question has changed to "Implementing content-negotiation in a RESTful AP".
Type 1: Controller-oblivious
Basically, if content negotiation involves only the format of the resource, implementing or using the right media type formatter is enough. For example, if content negotiation involves returning JSON or XML. In these cases, controller is oblivious to content negotiations.
Type 2: Controller-aware
Controller needs to be aware of the request negotiation. In this case, parameters from the request needs to be extracted from the request and passed in as parameter. For example, let's imagine this action on a controller:
public Player Get(string schemaVersion)
{
...
}
In this case, I would use classic MVC style value providers (See Brad Wilson's post on ValueProviders - this is on MVC but Web API's value provider looks similar):
public Player Get([ValueProvider(typeof(RequestHeadersSchemaValueProviderFactory))]string schemaVersion)
{
...
}

WCF service authentication method

I'm building a WCF SOAP service at the moment. I will, of course, need some authentication on the service.
Reading this very helpful blog post says that to use the built-in authentication points requires that the endpoint use the wsHttp binding.
This would be fine if I could guarantee that users would be communicating with the service through a client based on the meta-data exposed by WCF (basically, something like a client written in C# with a web service reference). However, I can't guarantee this!
I will still need to allow users to communicate with just raw (unencrypted) XML.
So, questions:
Does the wsHttp binding still allow for raw XML input?
If not, would I be wiser to
Implement two separate authetication points? One for raw XML input and one for encrypted input
Or
Allow input from wsHttp to fall back on some in-method validation that would be shared with the raw XML input?
Is it wise to allow users to pass their credentials inside a raw XML request?
EDIT: It sounds like I miscommunicated or misunderstood something in my original post, so here I will clarify what I mean by "raw XML".
By raw XML, I mean just the SOAP packet and the accompanying HTTP headers - as I might send from soapUI or Fiddler. As I understand it, messages over the wsHttp binding are encrypted when a client is generated from the WSDL (for example, in C#).
If this is not the case, then how would I go about attaching the same sorts of credentials to a raw XML (for want of a better term) request as I do a request run through a client? Are they attached as HTTP headers? XML elements in the SOAP envelope?
wsHttp is a SOAP binding, which means that your content gets wrapped in a SOAP envelope, possibly with headers relating to the message and various WS-* specifications being used.
I would ask why you need to support raw XML? Most platforms today support SOAP messaging and the whole idea of SOAP is to provide interoperability between different platforms. On most platforms it is as easy to develop a SOAP client as a raw XML client. In most cases, it is simply a case of taking the WSDL and generating a client. If you want to use standard facilities like authentication and message encryption then this is a much better way to go.
There are currently no hooks to do interoperable authentication for raw XML. You will have to come up with your own mechanism to do this and it will be non-standard. For your web service users, this means it will be probably entail more development effort than if you just went with SOAP.

Is WCF result as JSON + unparseable curft needed for better security? How is it implemented?

I'm reading about this ajax response that describes ways to prevent Javascript based exploits.
Does it make sense to apply this technique to WCF-based services that return JSON?
How would this be implemented server side?
How would the client consume it?
There's one way WebScriptEnablingBehavior -- the behavior of choice if you want a WCF service that works with ASP .NET AJAX -- deals with this. By default, its response mode is "WrappedResponse". If you watch this in action using Fiddler, it means that every response from the service -- even a simple number -- will wrapped in {d:} wrapper as follows:
{ "d" : return-value }
On the other hand, WebHttpBehavior is XML out-of-the-box, but if you switch it to JSON, you can choose between WrappedResponse and BareResponse. WrappedResponse is similar to WebScriptEnablingBehavior (if I remember correctly), but BareResponse would be unsecure JSON transmitted back as a direct return value.

Best way to support "application/x-www-form-urlencoded" post data with WCF?

I'm building a WCF service based on a W3C specification which defines a RESTful web service endpoint that accepts "application/x-www-form-urlencoded" post data. WCF doesn't support this type of message encoding by default and I have found a number of different examples of creating a contract that looks like this:
XElement Query_Post(Stream postData);
And then within the implementation decoding the postData stream using the HttpUtility.ParseQueryString method.
Does anyone know of a more strongly typed way of supporting "application/x-www-form-urlencoded" in WCF?
I would like my operation contract to be:
XElement Query_Post(string query, string [] params);
The best way is to use Stream like Raw HTTP POST with WCF or what you are saying.
The reason is because WCF abstracts all the communication-level physical layout stuff out from the service code. Ideally, you would want to make a service that could turn into SOAP or REST just by flipping the switch.
To support it natively, you probably have to extend WebHttpBinding or make your own binding and implement custom encoder. This is symmetric to the output like the linked post says. You have to twist its arms to get WCF to output non-XML/JSON stuff.
The WCF REST Contrib library enables this functionality:
https://github.com/mikeobrien/WcfRestContrib
It includes a POX formatter and form url encoded formatter and allows you to easily create your own. Formatters are mapped to mime types and automatically selected to serialize/deserialize the entity body based on the content type and accept headers.