大家好,感谢您的关注。我写了一个返回 FileStreamResult 或 NotModified 状态代码的操作,它在 Postman 中有效,但如果我使用 C# 代码,它就不起作用。
[HttpGet("{id}")]
public async Task<IActionResult> Get(Guid id, [FromServices] IContentTypeProvider contentTypeProvider)
{
string? hash = Request.Headers.IfNoneMatch;
long userId = long.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
FileDto fileDto = await _fileService.GetMetadataAsync(id, userId);
if (fileDto.Hash == hash)
{
return StatusCode((int)HttpStatusCode.NotModified);
}
Stream stream = await _fileService.GetStreamAsync(id, userId);
string? contentType;
if (contentTypeProvider.TryGetContentType(fileDto.Name, out contentType) is not true)
{
contentType = "application/octet-stream";
}
Response.Headers.CacheControl = "public";
Response.Headers.ETag = fileDto.Hash;
return new FileStreamResult(stream, contentType)
{
FileDownloadName = fileDto.Name,
};
}
HttpClient(和WebClient)的行为很奇怪:
2. Etag 为空,但如果将响应序列化为 JSON,则表明 Etag 存在于响应标头中。
序列化响应:
{
"Version": "1.1",
"Content": {
"Headers": [
{
"Key": "Content-Length",
"Value": [
"0"
]
},
{
"Key": "Content-Type",
"Value": [
"image/jpeg"
]
},
{
"Key": "Content-Disposition",
"Value": [
"attachment; filename=shrek.jpg; filename*=UTF-8\u0027\u0027shrek.jpg"
]
}
]
},
"StatusCode": 200,
"ReasonPhrase": "OK",
"Headers": [
{
"Key": "Date",
"Value": [
"Fri, 21 Apr 2023 11:36:24 GMT"
]
},
{
"Key": "Server",
"Value": [
"Kestrel"
]
},
{
"Key": "Cache-Control",
"Value": [
"public"
]
},
{
"Key": "ETag",
"Value": [
"DA39A3EE5E6B4B0D3255BFEF95601890AFD80709"
]
}
],
"TrailingHeaders": [],
"RequestMessage": {
"Version": "1.1",
"VersionPolicy": 0,
"Content": null,
"Method": {
"Method": "GET"
},
"RequestUri": "https://localhost:201/api/files/ad71424e-3ac1-47cd-b36d-107deadce4f2",
"Headers": [
{
"Key": "Authorization",
"Value": [
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoic2Vjb25kVXNlckRvd25sb2FkRmlsZUB3aXRoQWNjZXNzRmlsZS50ZXN0Iiwic3ViIjoiMiIsImp0aSI6ImRhZDUxMTNlLWFiOWYtNDRlMS1iMTI2LTE0OWZjYzRhNDk2OCIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6IkVtYWlsIENvbmZpcm1lZCIsImV4cCI6MTY4MjA3Nzg4NSwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6MjAxIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6MjAxIn0.MBiMYbOuZkEkwJKySNTBqczPPjEQfGyVi_G1jPw6vnk"
]
}
],
"Properties": {},
"Options": {}
},
"IsSuccessStatusCode": true
}
为什么 Postman 工作但 HttpClient(WebClient 也是)不工作?也许我错过了什么?