如何转发的Htt prequestMessage到另一台服务器 [英] How to forward an HttpRequestMessage to another server

查看:211
本文介绍了如何转发的Htt prequestMessage到另一台服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是转发的web API请求到另一台服务器的最佳方式?

What's the best way to forward an http web api request to another server?

下面就是我想:

我在那里的时候,我得到一定的API请求我想修改的请求,将其转发到另一台服务器,并返回由第二服务器发送的响应.NET项目。

I have a .NET project where when I get certain API requests I want to modify the request, forward it to another server, and return the response sent by that second server.

我做以下内容:

[Route("forward/{*api}")]
public HttpResponseMessage GetRequest(HttpRequestMessage request)
{
    string redirectUri = "http://productsapi.azurewebsites.net/api/products/2";
    HttpRequestMessage forwardRequest = request.Clone(redirectUri);

    HttpClient client = new HttpClient();
    Task<HttpResponseMessage> response = client.SendAsync(forwardRequest);
    Task.WaitAll(new Task[] { response } );
    HttpResponseMessage result = response.Result;

    return result;
}

当克隆方法被定义为:

Where the Clone method is defined as:

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);
    }

    return clone;
}

然而,出于某种原因,而不是URL重定向到指定的redirectUri我得到那里的RequestMessage.RequestUri设置为 HTTP 404响应://本地主机:61833 / API /产品/ 2 。 (的http://本地主机:61833 是原始请求的URI的根目录)。

However, for some reason instead of redirecting the url to the specified redirectUri I get a 404 response where the RequestMessage.RequestUri is set to http://localhost:61833/api/products/2. (http://localhost:61833 is the root of the original request uri).

感谢

推荐答案

您可能需要显式设置克隆实例的主机头。否则,你只是复制对面的克隆原始请求的主机头值。

You might need to explicitly set the host header on the clone instance. Otherwise you are just copying the original request's host header value across to the clone.

即。下面一行添加到您的克隆方法的末尾:

i.e. add the following line to the end of your Clone method:

clone.Headers.Host = new Uri(newUri).Authority;

此外,根据你正试图在这里实现什么,你可能还需要处理其他问题,如对不符合你要转发到新域名请求的cookie域以及设置任何响应cookie的正确域被返回。

Also, depending on what you are trying to achieve here, you may also need to handle other issues like cookie domains on the request not matching the new domain you are forwarding to as well as setting the correct domain on any response cookies that are returned.

这篇关于如何转发的Htt prequestMessage到另一台服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆