Csharp/C#教程:无法使用带有GET请求的动词类型发送内容正文分享


无法使用带有GET请求的动词类型发送内容正文

我目前正通过WebApi收到请求,并试图将其重新发送到另一个站点。

目标是通过示例接收请求: http:// localhost:9999 / #q = test 。 然后将其转发到真实网站:(我的测试我设置了google.com) https://google.com/#q=test

我有以下代码:

protected override async Task 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请求。

那么为什么这个例外会来呢? 有关如何解决它的任何想法?

我最后创建了初始请求的副本,然后再次发送:

 protected override async Task 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; } 

克隆方法如下,主要来自这个问题: 如何将HttpRequestMessage转发到另一台服务器

上述就是C#学习教程:无法使用带有GET请求的动词类型发送内容正文分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  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 prop in req.Properties) { clone.Properties.Add(prop); } foreach (KeyValuePair> header in req.Headers) { clone.Headers.TryAddWithoutValidation(header.Key, header.Value); } clone.Headers.Host = new Uri(newUri).Authority; return clone; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/942272.html

(0)
上一篇 2021年11月13日
下一篇 2021年11月13日

精彩推荐