Home > Enterprise >  My .NET Core 7 controller is displaying an error in Swagger
My .NET Core 7 controller is displaying an error in Swagger

Time:01-18

Undocumented
TypeError: Window.fetch: HEAD or GET Request cannot have a body.

The C# code in the controller. It won't even hit my debug point at var results.

    [HttpGet(Name = "GetAccountBalance")]
    public async Task<ActionResult<BankTransactionDto>> GetAccountBalance(BankTransactionDto bankDto)
    {
        var results = await _bankTransactionService.GetTotalBalance(bankDto);
        return Ok(results);
    }

enter image description here

CodePudding user response:

Undocumented TypeError: Window.fetch: HEAD or GET Request cannot have a body.The C# code in the controller. It won't even hit my debug point at var results.

Issue Reproduced:

I have tried to reproduce your issue and successfully simulated as expected. As you can see below:

enter image description here

Why Not Working:

Well, the error you are getting is pretty obvious in reagrds of enter image description here

Note: If you need more information, you could refer to following official documnet.

  1. Asp.net core web API Http verb Request Body format.
  2. Swagger Request Body documnt

CodePudding user response:

You can't send a json with a GET request, because, as the error message specifies, it cannot have a body for historical reasons.

There's a proposal for a QUERY type request that will be similar to GET be will be able to include a body.

For now, you are limited to use other http verbs that accept bodies, or change the way you receive data to query parameters. For the later, you need to include the [FromQuery] decorator on your action parameter

public async Task<ActionResult<BankTransactionDto>> GetAccountBalance([FromQuery] BankTransactionDto bankDto)
{
    var results = await _bankTransactionService.GetTotalBalance(bankDto);
    return Ok(results);
}

And your request will have to be sent as

GET https://localhost:{port}/api/BankTransaction?id=0&bankId=0&customerId=0&transactionType=0&amount=0&memo=string

CodePudding user response:

Change the Action Method definition to something like this:

[HttpGet("{id}")]
public async Task<ActionResult<BankTransactionDto>> GetAccountBalance(int id)
{
    // Your code here, but changed to use the `id` value.
}

where id is the technical Id of the bank transaction.

It makes no sense to try to send an entire BankTransactionDto object to the Action Method if you want to retrieve one of such objects. All it needs is a value that uniquely identifies it and with which the BankTransactionDto can be retrieved, such as the id.

It could be that Swagger will now no longer show the Request.body area (not at my Dev PC right now, so I can't try). If it does still show it, then leave it empty.
Instead put a useful and valid id in the URL, like this: /api/BankTransaction/123.

  • Related