I have a web api, where the global configuration is configured to use: XmlMediaTypeFormatter
My problem is I wont to extend this web api with a new controller, that uses the JsonMediaTypeFormatter instead.
Is it possible to change the MediaTypeFormatter to JSON for only one API Controller class?
My problem is not returning JSON, I have accumplished this with returning HttpResponseMessage:
return new HttpResponseMessage
{
Content = new ObjectContent<string>("Hello world", new JsonMediaTypeFormatter()),
StatusCode = HttpStatusCode.OK
};
It's on the request I get the problem. If I have an object with two properties:
public class VMRegistrant
{
public int MerchantId { get; set; }
public string Email { get; set; }
}
And my controller action takes the VMRegistrant as argument:
public HttpResponseMessage CreateRegistrant(VMRegistrant registrant)
{
// Save registrant in db...
}
But the problem is when I call the action with JSON it fails.
Yes, it's possible to change the
MediaTypeFormatters
for only one class/controller. If you want to save and restore the default formatters you can follow these steps:I think this is easily done by an
ActionFilterAttribute
:And the usage:
You can have your controller return an
IHttpActionResult
and use the extension methodHttpRequestMessageExtensions.CreateResponse<T>
and specify the formatter you want to use:Another possibility is to use the
ApiController.Content
method:Edit:
One possibility is to read and deserialize the content yourself from the
Request
object via reading from tge stream and using a JSON parser such as Json.NET to create the object from JSON:Maybe you could have your media type formatter only accept the type that is handled by your controller:
Probably not the best solution though :I