我想为我的XmlHttpRequest操作创建一个basix代理处理程序。我正在创建一个delegg处理程序。
public class ProxyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var forwardUri = new UriBuilder(request.RequestUri);
request.RequestUri = forwardUri.Uri;
var client = new HttpClient();
var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);
return response;
}
}
配置
config.Routes.MapHttpRoute(
name: "Proxy",
routeTemplate: "{*path}",
handler: HttpClientFactory.CreatePipeline(
innerHandler: new HttpClientHandler(),
handlers: new DelegatingHandler[] { new ProxyHandler() }),
defaults: new { path = RouteParameter.Optional },
constraints: null
);
我想将请求转发到目标服务器。例如http://localhost:1123?path=http://another.web.api/controller
但抛出错误:
System.Net.ProtocolViolationException:无法发送内容正文 这个动词类型。
`?path=http://another.web.api/controller` request may be post get or put request.
答案 0 :(得分:2)
转发GET
请求时,您需要为传递给处理程序的请求将内容设置为null
。在执行null
时,请更新代码以检查请求方法和GET
内容。
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var path = request.GetQueryNameValuePairs().Select(x => x.Key == "path").FirstOrDefault();
var forwardUri = new UriBuilder(path);
request.RequestUri = forwardUri.Uri;
// Add this if block
if (request.Method == HttpMethod.Get)
{
request.Content = null;
}
var client = new HttpClient();
var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);
return response;
}