Unable to get header "Content-Disposition" with httpclient in C#
Asked Answered
N

2

8

SCENARIO:
First of all, please consider I'm using HttpClient class, not WebRequest, I know that there is a lot of related question here but all answers are for WebRequest.

I made a Web Api Application that set in this way the following header in order to download a .txt file:

resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
    FileName = _datacontext.GetAppConfig("814FileNameHeader") + DateTime.Now.ToString("yyyyMMdd") + ".txt"
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");  

After I made an HttpClient from other application to connect to this method.
Everything is working, retrieves 200 and the content of the file. But I can't get the header in order to read the filename.

TRIES MADE:

Working with a REST Client I can read the following header attribute:

Content-Disposition: attachment; filename=814Entes_PG_20160114.txt

and from the code I could debug it and I found that the header is in "invalidHeaders" but I can't reach the value:

enter image description here

QUESTION:

How can I set up this and getting without any doubt from the client?

UPDATE:

These are my tries to get the header: The original:

                using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(uri);
                string authentication = string.Concat(authenticationArgs[0], ":", authenticationArgs[1]);
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + Base64Encode(authentication));
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "Report/" + type);
                req.Content = new StringContent("");
                HttpResponseMessage response = await httpClient.SendAsync(req);
                Console.WriteLine(response.StatusCode);
                if (response.IsSuccessStatusCode)
                {
                    string stream = response.Content.ReadAsStringAsync().Result;
                    Console.Write("Respuesta servicio: " + stream);
                    Console.WriteLine(stream);

                  string cp =  response.Headers.GetValues("Content-Disposition").ToString();
                }

The second one I tried with some SO investigation:

        using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri(uri);
            string authentication = string.Concat(authenticationArgs[0], ":", authenticationArgs[1]);
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + Base64Encode(authentication));
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "Report/" + type);
            req.Content = new StringContent("");
            HttpResponseMessage response = await httpClient.SendAsync(req);
            Console.WriteLine(response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                string stream = response.Content.ReadAsStringAsync().Result;
                Console.Write("Respuesta servicio: " + stream);
                Console.WriteLine(stream);
                string cp = "";
                HttpHeaders headers = response.Headers;
                IEnumerable<string> values;
                if (headers.TryGetValues("Content-Disposition", out values))
                {
                    cp = values.ToString();
                }

            }
Neoteric answered 14/1, 2016 at 18:37 Comment(6)
Can you please show the code that makes the request and how you try to "get" the headers? Given Content-Length and Content-Type are also in the "invalid headers" collection, I'd suspect your request code.Overspill
sure, I didn't think that was, let me update my question. Done @Overspill thanks for your suggestion!Neoteric
just curious, but if the MediaTypeHeaderValue is application/octet-stream, shouldn't you read the response with ReadAsStreamAsync().Result?Incapacity
also, if you are trying to get the headers of the content.. shouldn't it be from response.Content.Headers?Incapacity
@Incapacity you are right, I forget the .content. Please make your comment answer in order to mark it as answer. Thanks a lot!Neoteric
@LeandroTupone no problem! I was working on a HttpClient passing back a pdf file, so I reviewed that and thought that might be itIncapacity
I
25

If you are trying to get the headers of the content, it should be from response.Content.Headers

Incapacity answered 14/1, 2016 at 19:24 Comment(3)
if the content-disposition header isnot exist. what should i do to make it exist ?Dispersion
@Dispersion the server which is serving the request needs to set the header for it to exist in the responseStilton
@Stilton does accessing response.Content.Headers cause the entire content to be read into memory? I am trying to avoid that. Thanks.Effie
V
2

As per @terbubbs you need response.Content.Headers.

But also code needs to be - for the first code sample:

string cp = response.Result.Content.Headers.GetValues("Content-Disposition").ToList()[0];

And for the second:

cp = values.FirstOrDefault().ToString();

Otherwise the result is System.String[]

Virtuosic answered 3/8, 2022 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.