情景:
首先,请考虑我使用HttpClient
课程,而不是WebRequest
,我知道这里有很多相关问题,但所有答案都是针对WebRequest的。
我制作了一个Web Api应用程序,以这种方式设置以下标题以便下载.txt文件:
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");
从其他应用程序创建HttpClient后连接到此方法 一切正常,检索200和文件的内容。但我无法获取标题以便读取文件名。
TRIES MADE:
使用REST客户端我可以阅读以下标题属性:
内容 - 处置:附件;文件名= 814Entes_PG_20160114.txt
从代码我可以调试它,我发现标题在" invalidHeaders"但我无法达到这个价值:
问题:
如何设置此设置并毫无疑问地从客户端获取?
更新:
这些是我尝试获取标题: 原文:
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();
}
第二个我尝试了一些SO调查:
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();
}
}
答案 0 :(得分:9)
如果您尝试获取内容的标题,则应该来自response.Content.Headers