Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an API proxy in ASP.NET MVC 6

I am migrating code from an existing WebApi 2 project and I am wondering how to perform the equivalent of the code below in ASP.NET 5 MVC 6. I don't see any route code which accepts a handler option.

config.Routes.MapHttpRoute("SomeApiProxy", "api/someapi/{*path}",
    handler: HttpClientFactory.CreatePipeline(new HttpClientHandler(), new DelegatingHandler[] {new ForwardingProxyHandler(new Uri("http://some-api.com/api/v2/"))}),
    defaults: new {path = RouteParameter.Optional},
    constraints: null
);
like image 383
Chris Putnam Avatar asked Jan 21 '16 19:01

Chris Putnam


1 Answers

This is just off the top of my head but you could create a middleware. This would work for get requests with no headers but could be modified to do more.

app.Use( async ( context, next ) =>
{
    var pathAndQuery = context.Request.GetUri().PathAndQuery;

    const string apiEndpoint = "/api/someapi/";
    if ( !pathAndQuery.StartsWith( apiEndpoint ) )
        //continues through the rest of the pipeline
        await next();
    else
    {
        using ( var httpClient = new HttpClient() )
        {
            var response = await httpClient.GetAsync( "http://some-api.com/api/v2/" + pathAndQuery.Replace( apiEndpoint, "" ) );
            var result = await response.Content.ReadAsStringAsync();

            context.Response.StatusCode = (int)response.StatusCode;
            await context.Response.WriteAsync( result );
        }
    }
} );

If you put this befire app.UseMvc() it will intercept any requests where the path starts with /api/someapi

like image 182
Jake Rote Avatar answered Oct 11 '22 13:10

Jake Rote