C#通用代理-http请求转发
[HttpPost]
[HttpGet]
[Route("OaProxy/{*uri}")]
[DontWrapResult(WrapOnError = false, WrapOnSuccess = false, LogError = true)]
public async Task OaProxy(string uri)
{
    var queryString = HttpUtility.ParseQueryString(Request.QueryString.Value);
    queryString.Add("key", AppConsts.oaKey);
    var requestUri = new Uri(String.Format("{0}?{1}", uri, queryString), UriKind.Relative);
    var requestMessage = new HttpRequestMessage();
    requestMessage.RequestUri = requestUri;
    requestMessage.Method = new HttpMethod(Request.Method);
    if (requestMessage.Method == HttpMethod.Post)
    {
        //requestMessage.Content = new StreamContent(Request.Body);
        var formContent = new List<KeyValuePair<string, string>>();
        foreach (var formKey in Request.Form.Keys)
        {
            var content = Request.Form[formKey].FirstOrDefault();
            formContent.Add(new KeyValuePair<string, string>(formKey, content));
        }
        requestMessage.Content = new FormUrlEncodedContent(formContent);
    }
    var client = _httpClientFactory.CreateClient("oa");
    var response = await client.SendAsync(requestMessage);
    Response.StatusCode = (int)response.StatusCode;
    foreach (var header in response.Headers)
    {
        Response.Headers[header.Key] = header.Value.First();
    }
    foreach (var header in response.Content.Headers)
    {
        Response.Headers[header.Key] = header.Value.First();
    }
    Response.Headers.Remove("transfer-encoding");
    Response.Headers.Remove("Content-Type");
    Response.Headers.Add("Content-Type", "application/javascript");
    await response.Content.CopyToAsync(Response.Body);
    Response.Body.Flush();
    Response.Body.Close();
}
参考:
- https://stackoverflow.com/questions/57214931/forward-post-request-from-asp-net-core-controller-to-different-url
- https://stackoverflow.com/questions/42000362/creating-a-proxy-to-another-web-api-with-asp-net-core
- https://stackoverflow.com/questions/44729592/how-to-forward-http-response-to-client
- https://stackoverflow.com/questions/697177/relaying-a-request-in-asp-net-forwarding-a-request/12506079
- https://github.com/aspnet/Proxy/blob/master/src/Microsoft.AspNetCore.Proxy/ProxyAdvancedExtensions.cs
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号