DelegatingHandler SendAsync在sendRequest之前更改RequestUri

时间:2014-08-11 08:59:38

标签: c# http httprequest asp.net-web-api

我尝试创建一个接受请求的网关然后将请求URL映射到配置模式并将请求uri更改为该新模式,它工作正常localHost但是当我将模式更改为域名时它返回404

protected override Task<HttpResponseMessage> SendAsync
         (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
    request.RequestUri = GetForwardToURL(request.RequestUri);
    if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Trace)
        request.Content = null;
    return base.SendAsync(request, cancellationToken);
}

//示例uri =&#34; http://myproxy.com/api-1/ ...&#34;

// patterns&#34; api-1&#34; =&#34; http://myproxy2.com&#34;

public Uri GetForwardToURL(Uri uri)
{
    var section = ConfigurationManager.GetSection("patterns") as NameValueCollection;

    foreach (var key in section.Keys)
    {
        if (uri.OriginalString.Contains(key.ToString()))
        {
            return new Uri(new Uri(section[key.ToString()]), uri.PathAndQuery);
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

我解决它只是我需要添加CRUD