A X
A X

Reputation: 1056

How to Create .NET Framework WebAPI Controller that responds to All Requests

We need to create a single Web API controller that responds to All Inbound Requests. This is so that we can create a reverse proxy of sorts where the incoming traffic is processed, then sent on to another server.

The approach we would like to use is .NET Framework Web API accepts the inbound request through a single controller, processes it, then sends it to the origin server, then when the response comes back return it to the client.

The proxy part is straightforward - but what I don't know how to do is configure the routing rules in Web API to accept all inbound traffic, across all methods (GET, POST, etc.) into a single controller.

Any help with this would be greatly appreciated.

Upvotes: 1

Views: 357

Answers (2)

Kahbazi
Kahbazi

Reputation: 15005

You can add a route to catch all request

config.Routes.MapHttpRoute(
    name: "default-catch-all",
    routeTemplate: "{*uri}",
    defaults: new { controller = "Home", action = "Handle" }
);

If only thing that you want is to have a proxy, web api is not the best option. You should write a middleware for that. Here's a simple version of proxy middleware

public class ProxyMiddleware : OwinMiddleware
{
    private static HttpClient _httpClient = new HttpClient();

    public ProxyMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(context.Request.Method), new Uri("http://SERVERURL/" + context.Request.Path));
        request.Content = new StreamContent(context.Request.Body);
        HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
        context.Response.StatusCode = (int)response.StatusCode;
        await response.Content.CopyToAsync(context.Response.Body);
    }
}

Upvotes: 0

Ben Matthews
Ben Matthews

Reputation: 531

I think a custom route like this should do the trick, you would need to define a controller though which I called custom in this example.

routes.MapRoute(
    name: "Custom",
    template:"{*AllValues}",
        defaults: new { controller = "Custom", action = "Custom" });
    });

Tested to work on asp.net-core 2.2, but I think it will work on other frameworks.

Upvotes: 1

Related Questions