我目前正在通过WebApi收到请求,并尝试将其重新发送到另一个网站。
目标是接收请求,例如:http://localhost:9999/#q=test。然后将其转发到真实网站:(对于我的测试,我设置了google.com)http://google.com/#q=test
我有以下代码:
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
string url = request.RequestUri.PathAndQuery;
UriBuilder forwardUri = new UriBuilder(_otherWebSiteBase);
forwardUri.Path = url;
if (request.Method == HttpMethod.Get)
{
//request.Method = HttpMethod.Post;
}
request.RequestUri = forwardUri.Uri;
request.Headers.Host = forwardUri.Host;
return await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);//_client is an HttpClient
}
目前我有一个System.Net.ProtocolViolationException
,其中说明:
Cannot send a content-body with this verb-type.
但我的输入请求是GET请求(应该是GET请求)。如果我发出POST请求,我就不再有例外了,但Google表示他们不希望发出POST请求。
那么为什么会出现这种异常呢?有关如何修复的想法吗?
答案 0 :(得分:4)
我最后创建了初始请求的副本,然后再次发送:
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
string url = request.RequestUri.PathAndQuery;
UriBuilder forwardUri = new UriBuilder(_otherWebSiteBase);
forwardUri.Path = url;
HttpRequestMessage newRequest = request.Clone(forwardUri.Uri.ToString());
HttpResponseMessage responseMessage = await _client.SendAsync(newRequest);
return responseMessage;
}
克隆方法如下,主要来自这个问题:How to forward an HttpRequestMessage to another server
public static HttpRequestMessage Clone(this HttpRequestMessage req, string newUri)
{
HttpRequestMessage clone = new HttpRequestMessage(req.Method, newUri);
if (req.Method != HttpMethod.Get)
{
clone.Content = req.Content;
}
clone.Version = req.Version;
foreach (KeyValuePair<string, object> prop in req.Properties)
{
clone.Properties.Add(prop);
}
foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers)
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
clone.Headers.Host = new Uri(newUri).Authority;
return clone;
}