1

对于一个项目,我需要为第三方 API 构建一个“代理”,因为应该为外部方阻止部分 API。现在我可以使用 HttpClient 从 API 中检索信息,但我需要使用 HttpResponse 将信息发回。在很多情况下,我可以将信息发回,但有时信息会以 gzip 或二进制文件的形式发回。我想要做的是将所有标头从 HttpResponseMessage 复制到 HttpResponse 但我失败了。有没有人做过这样的事情?

    public static void AddHeaders(HttpResponse httpResponse, System.Net.Http.HttpResponseMessage httpResponseMessage)
    {
        httpResponse.CacheControl = httpResponseMessage.Headers.CacheControl.ToString();

        foreach (KeyValuePair<string, System.Collections.Generic.IEnumerable<string>> item in httpResponseMessage.Headers)
        {
            AddHeaders(httpResponse, item);
        }

        foreach (KeyValuePair<string, System.Collections.Generic.IEnumerable<string>> item in httpResponseMessage.Content.Headers)
        {
            AddHeaders(httpResponse, item);
        }
    }

    public static void AddHeaders(HttpResponse httpResponse, KeyValuePair<string, System.Collections.Generic.IEnumerable<string>> keyValuePair)
    {
        string key = keyValuePair.Key;
        string values = "";
        foreach (string stringValue in keyValuePair.Value)
        {
            values += "," + stringValue;
            values = values.Trim(',');
        }
        switch (key)
        {
            case "Content-Type":
                httpResponse.ContentType = values;
                break;
            default:
                httpResponse.Headers.Add(key, values);
                break;
        }
    }
4

0 回答 0