将HTTP请求转发给另一台服务器

时间:2017-11-28 12:37:58

标签: c# asp.net http http-post

我有以下接收webhook消息的代码:

// Read posted data
string requestBody;
using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
    requestBody = reader.ReadToEnd();
}
requestBody.Log();

// Attempt to forward request
context.CopyTo(Settings.Payments.Paypal.ScirraPaypalIPNEndpoint);

requestBody包含记录的数据。然后我尝试将请求转发到另一个URL:

    public static void CopyTo(this HttpContext source, string url)
    {
        var destination = (HttpWebRequest) WebRequest.Create(url);

        var request = source.Request;
        destination.Method = request.HttpMethod;

        // Copy unrestricted headers
        foreach (var headerKey in request.Headers.AllKeys)
        {
            if (WebHeaderCollection.IsRestricted(headerKey)) continue;
            destination.Headers[headerKey] = request.Headers[headerKey];
        }

        // Copy restricted headers
        if (request.AcceptTypes != null && request.AcceptTypes.Any())
        {
            destination.Accept = string.Join(",", request.AcceptTypes);
        }

        destination.ContentType = request.ContentType;
        destination.Referer = request.UrlReferrer?.AbsoluteUri ?? string.Empty;
        destination.UserAgent = request.UserAgent;

        // Copy content (if content body is allowed)
        if (request.HttpMethod != "GET"
            && request.HttpMethod != "HEAD"
            && request.ContentLength > 0)
        {
            using (var destinationStream = destination.GetRequestStream())
            {
                request.InputStream.Position = 0;
                request.InputStream.CopyTo(destinationStream);
                destinationStream.Close();
            }
        }

        if (!Settings.Deployment.IsLive)
        {
            ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) => true;
        }

        using (var response = destination.GetResponse() as HttpWebResponse)
        {
            if (response == null) throw new Exception("Failed to post to " + url);
        }
    }

接收此转发请求的处理程序具有以下代码:

public void ProcessRequest(HttpContext context)
{
    string requestBody;
    using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
    {
        requestBody = reader.ReadToEnd();
    }
    requestBody.Log();
}

但是,在转发给的处理程序中,requestBody始终为空!我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

两个服务器都托管在Clouflare中,当从一个服务器发布到另一个服务器时,我收到了CF 1000禁止的IP错误。

解决方案是将目标服务器IP地址添加到请求服务器主机文件中。