How to disable XML serialization in azure functions

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

This is to be expected, since the answer contains, among other things, a JObject that can be serialized for JSON just fine, but not for XML, and the Accept header in the browser prefers to use XML over JSON.

I can use a workaround to get the right answer, running off with the Accept (inserting application/json;q=0.95) browser header , but I really want to disable XML serialization in Azure Function, since my function will not be XML compatible anyway.

Is there a way to remove or disable XML formatting in Azure Functions so that it β€œforgets” that it can be serialized in XML, and anyone application/xmlin the request header is ignored? And instead, JSON formatting takes precedence despite a request to give preference to XML?

+4
source share
1 answer

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

So instead

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

I had to write

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

to get the behavior I wanted.

+1
source

Source: https://habr.com/ru/post/1671650/


All Articles