The business request is to enable accepting a request which will have two different types of content/type
in its request header.
So I tried with [Consumes()]
annotation, but swagger throws an error.
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesDefaultResponseType]
[Route(nameof(GetXmlInvoice))]
//[Consumes("application/xml")]
[HttpGet]
public async Task<IActionResult> GetXmlInvoice([FromQuery] long apiKeyId, [FromQuery] int inId)
{
//...some code
}
Approach #1: To have one method, and somehow read content/type that I receive
Approach #2: To have two methods with same signature, but different [Consumes("xml or json")]
part?
I tried approach #1 and my swagger didn’t like the idea to have two “same methods” with same name, I got an error for swashbuckle.
I would like to have approach #1 if possible.
What would be a correct way for implementing two behaviors based on content/type that I receive?
Thanks
If you want to let the controller to return both XML or Json format response.
I suggest you could use the AddXmlSerializerFormatters method which will enable XML or json based on your accept header.
Modify the program.cs:
builder.Services.AddControllers().AddXmlSerializerFormatters();
Result:
XML:
Json:
How about having one private method that contains all the logic but with none of the
[attributes]
. Then have two properly attributed methods that simple call the private methodCan you give an answer on this? I think its not quite I’m looking for. Because I need logic separation when I receive the request on controller side.
Content-Type header should not be used for HTTP GET method. Maybe you meant Accept? In requests, (such as POST or PUT), the client tells the server what type of data is actually sent. But in GET you actually don’t send any data in payload
content-type
header is for the responseaccept
shall be used for the client to indicate their preferred response content-type.Stack Overflow is not a free code writing service. You are expected to try to write the code yourself. After doing more research if you have a problem you can post what you’ve tried. All answers are here learn.microsoft.com/en-us/aspnet/core/web-api/advanced/…
Show 4 more comments