0

I am uploading a file to server. I have set FileName as custom header into my HttpRequestMessage. I am unable to read this header on server side.

using (FileStream fs = new FileStream(file, FileMode.Open))
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:54616/");

    HttpContent fileContent = new StreamContent(fs);
    HttpRequestMessage httpMsg = new HttpRequestMessage(HttpMethod.Post, "Api/FileHandler");
    httpMsg.Content = fileContent;
    httpMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    httpMsg.Content.Headers.Add("FileName", Path.GetFileName(file));

    var httpTask = client.SendAsync(httpMsg).Result;
}

On Server Side:

var input = Request.Content.ReadAsStreamAsync().Result;
var allHeaders = Request.Content.Headers.GetValues("FileName").ToList();

It throws InvalidOperation exception.

Abhijeet
  • 13,562
  • 26
  • 94
  • 175
  • possible duplicate of [How to extract custom header value in Web API message handler?](http://stackoverflow.com/questions/14967457/how-to-extract-custom-header-value-in-web-api-message-handler) – Aditya Singh Jul 23 '14 at 09:18
  • 1
    @wizkid Not a duplicate, I have similar code as suggested in the answer there but when running I get `InvalidOperation Exception` – Abhijeet Jul 23 '14 at 09:22
  • 1
    Use `Request.Headers` – Dai Jul 23 '14 at 09:23

1 Answers1

2

You have to realize that HttpContentHeaders is wrapping the headers that are Content headers. You cannot expect to add your custom ('FileName') header to it and read it later.

Use the regular Headers collection instead:

// write
httpMsg.Headers.Add("FileName", Path.GetFileName(file));

// read
var fileHeaders = Request.Headers.GetValues("FileName").ToList();

Or, if you insist on HttpContentHeaders, use its ContentLocation property which returns a Uri:

// write
httpMsg.Content.Headers.ContentLocation = new Uri(file);

// read
Uri file = Request.Content.Headers.ContentLocation;

Also, before reading your header value, it's always recommended to check whether that header exists at all (so you'll avoid the Exception):

if (Request.Headers.Contains("FileName"))
    fileHeaders = Request.Headers.GetValues("FileName").ToList();
haim770
  • 48,394
  • 7
  • 105
  • 133