mushroom
mushroom

Reputation: 6289

How to handle multiple content types in a single controller action in Play 2

In my Play Framework 2 application, I would like to have a single controller action handle multiple types of requests (JSON and URL encoded value). I have gotten this to work to some extent by pattern matching on the content type:

request.contentType match {
      case Some("application/json") => { /* Do some stuff with JSON ... */ }
      case _ => { /* Treat it like a regular html form ... */ }
}

This works, but doesn't seem like a great approach. I haven't been able to get the result types to be different yet (return JSON when I get JSON and HTML when I get a form submission).

How do people typically handle this situation in Play? Is it discouraged?

Upvotes: 5

Views: 541

Answers (1)

johanandren
johanandren

Reputation: 11479

I think that if it was XML/JSON for example then it would feel less strange then form-post/JSON.

In a normal Action you will have had to parse the body already to get an instance of Request. This makes what you describe a bit hard but you could probably pull it off creating an EssentialAction that looks at the RequestHeader and selects a body parser from that and passes of the parsed body to callback functions.

If you decide to go down that path I would recommend looking at the action composition part of the docs (http://www.playframework.com/documentation/2.2.x/ScalaActionsComposition) and the sources for the involved classes (you have them in your play installation).

Upvotes: 1

Related Questions