4

When I access my azure function (C# HttpTrigger) from my browser I get an XML response with an error message instead of a JSON response.

That is to be expected, since the response contains, amongst others, a JObject, which can be serialized to JSON just fine, but not to XML, and the browser's Accept header asks to prefer XML over JSON.

I can use a workaround to get the correct response by fiddling with the browser's Accept header (inserting application/json;q=0.95), but what I really want is to disable XML serialization in the Azure Function, since my function is not going to be XML compatible anyway.

Is there a way to remove or disable the XML formatter in Azure Functions so it "forgets" that it can serialize to XML, and any application/xml in the request header is ignored? And instead make the JSON formatter take precedence, despite the request asking to prefer XML?

polkduran
  • 2,533
  • 24
  • 34
Luc C
  • 1,133
  • 8
  • 22
  • Return your actual POCOs, not the serializer's classes. Json is just a string with a certain format. It *can* be added to an XML document, just like any other string. `JObject` on the other hand is *not* a Json string, it's an object used by one specific serialization library. It's the equivalent of trying to return an XmlDocument. Just do as you would do in ASP.NET MVC or Web API - return a POCO and let the framework decide how to serialize based on the requested format – Panagiotis Kanavos Mar 07 '17 at 08:24
  • Besides, if you don't want XML, stop asking for it. Don't try to break the server, fix the client – Panagiotis Kanavos Mar 07 '17 at 08:25

1 Answers1

2

With a bit of digging I found a working answer. It turns out that the HttpRequestMessageExtensions.CreateResponse extension method (extending HttpRequestMessage) has several overloads, and some of them allow specifying the resulting media type explicitly.

So instead of

return req.CreateResponse(HttpStatusCode.OK, returnObject);

I had to write

return req.CreateResponse(HttpStatusCode.OK, returnObject, "application/json");

to get the behavior I wanted.

Luc C
  • 1,133
  • 8
  • 22