I'm currently receiving a request through the WebApi, and trying to just resend it to another site.
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
I've the following 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
}
Currently I got an System.Net.ProtocolViolationException
which states: Cannot send a content-body with this verb-type.
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;
}
The clone method is the following, mostly inspired from this question: 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.