1

For a project I need to build a "proxy" for an third party API because parts of the API should be blocked for an external party. Now I can use HttpClient to retrieve the information from the API but I need to send the information back using HttpResponse. For a lot I can send information back but sometimes the information is send back as gzip or binary. What I'm trying to do is copying all Headers from HttpResponseMessage to HttpResponse but I fail miserably. Does anyone done something like this?

    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;
        }
    }
LiQuick.net
  • 189
  • 15
  • What do you mean you "fail miserably"? How does your code not perform as expected? – mason Feb 16 '19 at 14:51
  • Sorry for not being specific. When I get XML back the browser will format it correctly, but JSON will be displayed as HTML and when I receive content in GZIP, my Chrome browser reports: ERR_INVALID_CHUNKED_ENCODING. I think I'm not copying all header information from the HttpResponseMessage to the HttpResponse object correctly. – LiQuick.net Feb 16 '19 at 14:57
  • So, did you check? Why not look at the responses and compare them? Figure out what's different. – mason Feb 16 '19 at 14:58
  • Actually I did but I'm not sure which headers I need to "copy" so I was trying to copy all using above code. But HttpResponse has its own properties that partly are used as headers. The headers from HttpResponseMessage are in String while HttpResponse use Enums for a few (and tried to Parse but that won't work because the strings vary from the Enums) – LiQuick.net Feb 16 '19 at 15:02

0 Answers0