在ASP.NET MVC 6中创建API代理

Chr*_*nam 9 c# asp.net-web-api asp.net-core-mvc asp.net-core

我正在从现有的WebApi 2项目迁移代码,我想知道如何在ASP.NET 5 MVC 6中执行以下代码的等价物.我没有看到任何接受处理程序选项的路由代码.

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
);
Run Code Online (Sandbox Code Playgroud)

Jak*_*ote 9

这只是我的头脑,但你可以创建一个中间件.这适用于没有标题的get请求,但可以修改以执行更多操作.

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 );
        }
    }
} );
Run Code Online (Sandbox Code Playgroud)

如果你把这个befire app.UseMvc()它拦截路径以/ api/someapi开头的任何请求

  • 我试图将它构建成可以为每个人重用的东西.你可以在GitHub上找到它:https://github.com/ZoolWay/GlacierCrates.AspNetCore.ApiProxy (3认同)