如何在没有控制器的情况下仅通过DelegatingHandler创建WebApi?

时间:2019-01-22 16:42:19

标签: c# asp.net-web-api2 reverse-proxy

我正在尝试创建 SelfHost WebApi 2.0 (不是.net Core)用于反向代理。该api没有任何控制器,相反,我创建了一个DelegatingHandler,它将请求转发到其他地方。

这是代理处理程序

class ProxyHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return await RedirectRequest(request, cancellationToken).ConfigureAwait(false);
    }

    private async Task<HttpResponseMessage> RedirectRequest(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var redirectLocation = "http://localhost:8099";

        using (var client = new HttpClient())
        {
            using (var cloned = await CloneHttpRequestMessageAsync(request).ConfigureAwait(false))
            {
                cloned.RequestUri = new Uri($"{redirectLocation}{request.RequestUri.PathAndQuery}");
                return await client.SendAsync(cloned, cancellationToken).ConfigureAwait(false);
            }
        }
    }

    private async Task<HttpRequestMessage> CloneHttpRequestMessageAsync(HttpRequestMessage request)
    {
        var clone = new HttpRequestMessage(request.Method, request.RequestUri);

        if (request.Content != null)
        {
            var stream = new MemoryStream();
            await request.Content.CopyToAsync(stream).ConfigureAwait(false);
            stream.Position = 0;

            if ((stream.Length > 0 || request.Content.Headers.Any()) && clone.Method != HttpMethod.Get)
            {
                clone.Content = new StreamContent(stream);

                if (request.Content.Headers != null)
                    foreach (var h in request.Content.Headers)
                        clone.Content.Headers.Add(h.Key, h.Value);
            }
        }

        clone.Version = request.Version;

        foreach (var prop in request.Properties)
            clone.Properties.Add(prop);

        foreach (var header in request.Headers)
            clone.Headers.TryAddWithoutValidation(header.Key, header.Value);

        return clone;
    }

}

但是,我无法在配置中进行“全部捕获”路由,我尝试过: config.MessageHandlers.Add(new ProxyHandler());

var handler = HttpClientFactory.CreatePipeline(new HttpClientHandler(), new[] { new ProxyHandler() });
config.Routes.MapHttpRoute("default", "{*path}", null, null, handler);

ProxyHandler被调用,但是客户端收到404 http错误:未找到此请求的路由数据

如何创建不需要控制器且所有请求都发送到ProxyHandler的配置?

0 个答案:

没有答案