F
F
FairyFox57002020-04-18 09:27:34
ASP.NET
FairyFox5700, 2020-04-18 09:27:34

How to wrap responses in web Api .Net Core, so that in the case of no errors, you get data, and with errors, information about the error?

The crux of the issue is that now I'm returning IActionResult in my methods
For example:

// GET /api/Person
        [HttpGet]
        public async Task<ActionResult<IEnumerable<PersonDTO>>> GetAllPersons()
        {
            var persons = await personService.GetAllPersons();
            logger.LogInformation("Successfully returned all persons");
            return persons;
        }

I also check the model for validity.
But in case of an error, the code is repeated in many places and I can only display the status code, which is not very convenient:
if (id != person.Id)
            {
                return BadRequest();
            }
 или
if(ModelState.IsValid)
{
//что-то там
}

Are there any better ways to do this. Perhaps add filters or generic responses?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Django Almighty, 2020-04-23
@FairyFox5700

First, forget about returning through the task of some kind of ienumerable. Use IActionResult and only that.
In it, you can successfully throw either return Ok("Message from server, blah blah"), or return Badrequest("Something went wrong" + error.Message).
I think you'll get further. If you write. Always happy to help.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question