【发布时间】:2018-04-25 21:10:53
【问题描述】:
我的 WEB API 2 到 Angular 应用程序的 CORS 存在问题。 到目前为止一切正常,所有响应标头都收到以下内容:
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:24
Content-Type:application/json; charset=utf-8
Date:Mon, 13 Nov 2017 08:15:32 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?...
现在我像这样创建了一个自定义 IHttpActionResult:
public class ZipFileActionResult : IHttpActionResult
{
private const long BufferLength = 65536;
public ZipFileActionResult(string file)
{
this.Filepath = file;
}
public string Filepath { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage result = new HttpResponseMessage();
var zipf = new FilesStream(this.Filepath);
Action<Stream, HttpContent, TransportContext> writeToStream = zipf.WriteToStream;
result.Content = new PushStreamContent(writeToStream, new MediaTypeHeaderValue("application/" + "zip"));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "filename.zip"
};
return Task.FromResult(result);
}
private async void OnStreamConnected(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[BufferLength];
using (var nypdVideo = File.Open(this.Filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var videoLength = (int)nypdVideo.Length;
var videoBytesRead = 1;
while (videoLength > 0 && videoBytesRead > 0)
{
videoBytesRead = nypdVideo.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
await outputStream.WriteAsync(buffer, 0, videoBytesRead);
videoLength -= videoBytesRead;
}
}
}
catch (HttpException ex)
{
return;
}
finally
{
// Close output stream as we are done
outputStream.Close();
}
}
}
我在我的 DownloadCONtroller 中这样使用它:
[HttpPost]
[Route("PaperCuts")]
public IHttpActionResult PaperCuts(List<SelectionObject> selections)
{
try
{
string sFileName = <filename> + ".zip";
return new ZipFileActionResult(sFileName);
}
}
catch (Exception ex)
{
throw ex;
}
}
当我正确调用此函数时收到以下错误:
请求的资源上不存在“Access-Control-Allow-Origin”标头。
我收到这个作为响应头:
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcUHJvamVjdHNcS25pcHNlbGtyYW50XEtuaXBzZWxrcmFudEFQSVxLbmlwc2Vsa3JhbnRBUElcYXBpXGRvd25sb2FkXFBhcGVyQ3V0cw==?=
X-Powered-By: ASP.NET
Date: Mon, 13 Nov 2017 08:35:33 GMT
我的 WebApiConfig.cs 中也说明了这一点(它适用于除此之外的所有其他请求)。
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
所以问题是 Access-Control-Allow-Origin 标头等与所有其他请求中的不同。那么这怎么可能,我该如何解决呢? 我希望我为我的问题提供了足够的信息。
亲切的问候,
D.
【问题讨论】:
-
我今天发现了同样的问题。你解决了吗?
-
在此处找到解决方案:stackoverflow.com/questions/24189315/… 必须将 ShouldHandle 设置为始终返回 true。
-
正确的@ICantSeeSharp ,我也使用了这个解决方案。我忘了在这里提到我的解决方案。谢谢你提醒我!
标签: http-headers asp.net-web-api2 httpresponse asp.net-apicontroller