Asp.net Web api委托hangles作为代理

时间:2017-02-14 06:17:15

标签: asp.net asp.net-web-api

我想为我的XmlHttpRequest操作创建一个basix代理处理程序。我正在创建一个delegg处理程序。

public class ProxyHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var forwardUri = new UriBuilder(request.RequestUri);

        request.RequestUri = forwardUri.Uri;

        var client = new HttpClient();

        var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);

        return response;
    }
}

配置

        config.Routes.MapHttpRoute(
            name: "Proxy", 
            routeTemplate: "{*path}", 
            handler: HttpClientFactory.CreatePipeline(
                    innerHandler: new HttpClientHandler(), 
                    handlers: new DelegatingHandler[] { new ProxyHandler() }),
            defaults: new { path = RouteParameter.Optional },
            constraints: null
        );

我想将请求转发到目标服务器。例如http://localhost:1123?path=http://another.web.api/controller

但抛出错误:

  

System.Net.ProtocolViolationException:无法发送内容正文   这个动词类型。

`?path=http://another.web.api/controller` request may be post get or put request.

1 个答案:

答案 0 :(得分:2)

转发GET请求时,您需要为传递给处理程序的请求将内容设置为null。在执行null时,请更新代码以检查请求方法和GET内容。

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    var path = request.GetQueryNameValuePairs().Select(x => x.Key == "path").FirstOrDefault();

    var forwardUri = new UriBuilder(path);

    request.RequestUri = forwardUri.Uri;

    // Add this if block
    if (request.Method == HttpMethod.Get)
    {
        request.Content = null;
    }

    var client = new HttpClient();

    var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);

    return response;
}