Pieterjan
Pieterjan

Reputation: 3591

.NET Service reference sending wrong accept header (text/plain)

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.

Now 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

.NET Swagger Client is sending an Accept:text/plain header

Usually 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:

A text/plain header is explicitly added to the request

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.

How I added 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

Answers (2)

Darkerone
Darkerone

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

Gordon Khanh Ng.
Gordon Khanh Ng.

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

  • SOAP = XML
  • REST = JSON

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

Related Questions