Reputation: 3591
I've created an ASP.NET Core web application, and installed + used the Swashbuckle.AspNetCore
version 6.1.5
Nuget package. This hosts the following openapi document on https://example.com/swagger/v1/swagger.json
.
Also my API supports content-negotiation.
Accept
header, or Accept: text/xml
header, the api will return an XML stringAccept: application/json
header, the api will return a JSON stringNow I've tried consuming my api through the swagger document:
You can then write a Main
like this:
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var httpClient = new System.Net.Http.HttpClient();
// httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var mintPlayerClient = new MintPlayer.Api.MintPlayerClient("https://mintplayer.com", httpClient);
var artists = await mintPlayerClient.ApiArtistListAsync(false);
}
Now when you debug the console app
ApiArtistListAsync
method in the swaggerClient
classclient_.SendAsync
callUsually it's like this:
Even when adding a DefaultRequestHeader
on the HttpClient
the response from the HttpClient is an XML, because it's explicitly added inside the SwaggerClient method:
And here is how the code is generated + the line where the Accept header is explicitly set (swaggerClient:430
). This is auto-generated code from adding the service-reference.
So why is the Accept header in the generated code explicitly set to text/plain
? Why isn't the default accept header value application/json
, since this is a REST service?
Upvotes: 1
Views: 1144
Reputation: 101
If you don't need "plain/text" output format, you can remove "plain/text" output formatter using :
services.AddMvc(options =>
{
options.OutputFormatters.RemoveType<StringOutputFormatter>();
})
Upvotes: 0
Reputation: 1680
I think you might want to check this on both side, client(your console) and server(your api project).
We all know that usually
But you're coding the whole things, total in-control of what being send and what being response.
Let's assume you client send Accept-Header which support both text/xml
and text/plain
(which as i understand here, you expect a response as text/plain
).
Then the server realize that your console is happy with either text/xml
and text/plain
, and the server itself support all kind of common format.
So it'll have to electing the most convenient format to response to the client.
Which in this case is text/xml
.
That's so, the console received and happy with text/xml
response format either way
And if that's the case, that I get you right, you want to receive text/plain
on the console, then make sure the only Accept
header sending out is text/plain
or do some custom logic on your API to choose the text/plain
format over others when sending response.
Upvotes: 1