问题描述
我目前正在接受通过的WebAPI的请求,并试图只需将它重新发送到另一个站点。
I'm currently receiving a request through the WebApi, and trying to just resend it to another site.
的目的是接收的请求,由例如:的http://本地主机:9999 /#q构成=测试。然后它着真正的网站:(我的测试,我设置google.com) http://google.com /#Q =测试
The goal is to receive a request, by example: http://localhost:9999/#q=test. And then forward it to the real site:(for my test I set google.com) http://google.com/#q=test
我有以下code:
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
的规定:无法用这个动词型发送的内容体。
Currently I got an System.Net.ProtocolViolationException
which states:Cannot send a content-body with this verb-type.
但我的输入请求是GET请求(也应该是一个GET请求)。如果我把一个POST请求,我没有异常了,但谷歌表示,他们不希望一个POST请求。
But my input request is a GET request(and should be a GET request). If I put a POST request, I don't have an exception anymore, but google says that they don't expect a POST request.
那么,为什么这个异常来了吗?就如何解决它的主意?
So why is this exception coming? Any idea on how to fix it?
推荐答案
我最终通过创建初始请求的副本,并重新发送它:
I ended by creating a copy of the initial request, and sending it again:
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;
}
的克隆方法如下,从这个问题主要是启发:<一href="https://stackoverflow.com/questions/21467018/how-to-forward-an-htt$p$pquestmessage-to-another-server">How转发的Htt的prequestMessage到另一台服务器
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;
}
这篇关于无法发送内容体与这个动词型与GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!