Question
Is there a way to programmatically invoke the ASP.NET Core request pipeline from within my own application, given I have a HTTP verb, the route, headers and body payload?
Background
There are use-cases where the WebAPI of our ASP.NET Core application is not accessible because the application is running behind a firewall or is otherwise not reachable.
To provide a solution for this scenario we want our application to poll some other service for "work-items" which then translate into API calls in our application.
Approaches I considered
- I could probably just ask DI to give me an instance of a controller and then invoke methods on it. Problems with this approach:
- Authorization attributes are not enforced. But it is important in our use-case to have the bearer token validated. So here the question would be: How to invoke programmatically the Authorization middleware?
- I would have to route the incoming work-items to the correct controller/method myself.
- Using the
Microsoft.AspNetCore.TestHost
package I could create aTestClient
which allows me to make requests to myself (see here). But there are a couple of uncertainties here:- The intended use-case of this
TestHost
is for integration testing. Is it safe to use this in a production environment? - Is it even possible to have such a
TestServer
running alongside the regular hosting? - What about thread-safety? Can I create multiple
TestClients
from a singleTestServer
instance and use them from different threads?
- The intended use-case of this
So I'm sure there must be a cleaner and more direct way to programmatically invoke the request pipeline from within my own application...
HttpClient
to make the new request? That is how you would make a request to an 'external' website e.g. github – AyrshireIHttpApplication
interface which has aProcessRequestAsync
method which apparently allows to push a request through the request pipeline. I will probably have a closer look at this and otherwise just use HttpClient to invoke my own API, as you suggested. – MewlProcessRequestAsync
approach looks pretty interesting. I have a similar use case and recently asked for some guidance #56207615. – ThawHtttpClient
to invoke my own endpoints). – Mewl