使用C#读取自定义HttpHeaders

时间:2014-07-23 09:14:13

标签: c# httpclient

我正在将文件上传到服务器。我已将FileName设置为自定义标头HttpRequestMessage。我无法在服务器端读取此标题。

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;
}

在服务器端:

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

抛出InvalidOperation异常。

1 个答案:

答案 0 :(得分:1)

您必须意识到HttpContentHeaders正在包装内容标头的标头。您不能指望将自定义('FileName')标头添加到其中并稍后阅读。

改为使用常规Headers集合:

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

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

或者,如果您坚持使用HttpContentHeaders,请使用其ContentLocation属性,该属性返回Uri

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

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

此外,在读取标题值之前,始终建议检查该标题是否存在(因此您将避免异常):

if (Request.Headers.Contains("FileName"))
    fileHeaders = Request.Headers.GetValues("FileName").ToList();