S
S
Senture2021-06-07 16:21:36
ASP.NET
Senture, 2021-06-07 16:21:36

ASP.NET Web API. How to wrap ControllerBase.BadRequest without dependency injection?

Hello! The task is as follows, I want to make a wrapper for BadRequest, passing an array of strings (errors), so that the front would receive the following format:

errMessage: [
"err1",
"err2"
]


You can do it like this: But in this case it's easy to typo and then look for why the front does not display an error. Therefore, I want to make a wrapper, I know that it is possible like this:
return BadRequest(new { errMessage = listError });


public class ListMessageRequest : ControllerBase
    {
        public IActionResult BadRequest(string[] message)
        {
            return base.BadRequest(new { errMessage =  message  });
        }
    }


But then you have to use DI, and after that, in each class where this wrapper is needed, initialize the ListMessageRequest class in the constructor and only after that, use it.

There is a second option, write a static class that will return an object with an array of errors and use it like this:
return BadRequest(FormatError.GetFormat(listError));


Actually a question. How can I make this wrapper return a BadRequest with an array object of error strings, but without such a dependency? Tell me in which direction you need to drip and what to read.

Thanks to all!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2021-06-07
@Senture

Add an Exception Filter to the call pipeline. And throw a Custom Exception, which the filter will catch and return the result you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question