繁体   English   中英

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

[英]Creating an API proxy in ASP.NET MVC 6

我正在从现有的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
);

这只是我的头脑,但你可以创建一个中间件。 这适用于没有标题的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 );
        }
    }
} );

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

我们实际上为此写了一个中间件(我们的实习生做了:)) https://github.com/aspnet/Proxy

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM