Web Api 2 个自定义 IHttpActionResult CORS。请求的资源上不存在 'Access-Control-Allow-Origin' header
Web Api 2 custom IHttpActionResult CORS. No 'Access-Control-Allow-Origin' header is present on the requested resource
我的 WEB API 2 到 Angular 应用程序的 CORS 有问题。
到目前为止一切正常,所有响应 header 都收到以下内容:
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;
}
}
我在正确调用此函数时收到以下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
我收到了这个回复 header:
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 header 等与所有其他请求不同。那么这怎么可能,我该如何解决呢?
我希望我为我的问题提供了足够的信息。
亲切的问候,
D.
我找到了答案并得到了@ICantSeeSharp 的提醒
我在全局异常处理程序中添加了以下代码:
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
我的 WEB API 2 到 Angular 应用程序的 CORS 有问题。 到目前为止一切正常,所有响应 header 都收到以下内容:
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;
}
}
我在正确调用此函数时收到以下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
我收到了这个回复 header:
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 header 等与所有其他请求不同。那么这怎么可能,我该如何解决呢? 我希望我为我的问题提供了足够的信息。
亲切的问候,
D.
我找到了答案并得到了@ICantSeeSharp 的提醒
我在全局异常处理程序中添加了以下代码:
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return true;
}