C# 使用AWS SDK for.NET或REST API从Amazon S3检索带有图像和样式表的HTML文件
我正在尝试使用AWS SDK for.NET从AmazonS3检索一些HTML文件。我可以得到HTML文件,但链接到网页的图像没有显示,也没有应用相关的样式表。现在,我明白为什么会这样。因为每个图像和样式表在Amazon s3中都是一个单独的对象,而我的代码只是为HTML文件创建预签名的URL:C# 使用AWS SDK for.NET或REST API从Amazon S3检索带有图像和样式表的HTML文件,c#,.net,amazon-s3,C#,.net,Amazon S3,我正在尝试使用AWS SDK for.NET从AmazonS3检索一些HTML文件。我可以得到HTML文件,但链接到网页的图像没有显示,也没有应用相关的样式表。现在,我明白为什么会这样。因为每个图像和样式表在Amazon s3中都是一个单独的对象,而我的代码只是为HTML文件创建预签名的URL: private void GetWebUrl() { var request = new GetPreSignedUrlRequest().WithBu
private void GetWebUrl()
{
var request =
new GetPreSignedUrlRequest().WithBucketName(bucketName)
.WithKey("test/content.htm");
request.WithExpires(DateTime.Now.Add(new TimeSpan(0, 0, 0, 50)));
var url = S3.GetPreSignedURL(request);
Iframe2.Attributes.Add("src", url);
}
访问与此HTML文件相关的图像和样式表的最佳方式是什么?我可以查找所有图像,然后使用上面的方法生成预签名的URL请求,但这不是一种有效的方法,我无法公开图像和样式表。还有其他人遇到过类似的问题吗?
另外,如果我使用RESTAPI对用户进行身份验证(使用身份验证头)是否更好,这样浏览器的头中将包含身份验证信息,并且我不必为每个对象创建预签名的URL。RESTAPI的一小段代码将非常有用。实现这一点的最佳方法是使用通用处理程序(.ASHX)。诀窍是将网页和相关对象的源更改为处理程序:
src:"StreamFile.ashx?file="ObjKey"
现在,要更改源,您可以更新旧的HTML文件并创建新的HTML文件,其源指向(StreamFile.ashx)通用处理程序,或者使用URL重写将旧URL写入新URL。这可以在IIS或web.config中完成。如果在IIS中完成,它将自动在web.config中添加代码
<system.webServer>
<rewrite>
<rules>
<rule name="Content">
<match url="DevelopmentContent/Course/([a-zA-Z0-9]+)" />
<action type="Rewrite" url="StreamFile.ashx/?file=course{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
因此,现在所有HTTP请求都将使用您的服务器作为代理。这是可行的,但它要求您将所有文件从S3流式传输到Web服务器。。。这是一个相当高的带宽和性能成本为您的Web服务器。作为替代方案,您可能希望查看为文件生成预签名URL,并允许webbrowser直接从S3中提取它们……我们打算使用本地浏览器缓存和Memcached来优化性能。我更喜欢预签名URL,但我们的系统设计和限制不允许这样做。
public void ProcessRequest(HttpContext context)
{
var response = Gets3Response(context.Request.QueryString["file"]);
if (response != null)
{
using (response)
{
var mimEtype = response.ContentType;
context.Response.ContentType = mimEtype;
using (var responseStream = response.ResponseStream)
{
var buffer = new byte[8000];
var bytesRead = -1;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
context.Response.OutputStream.Write(buffer, 0, bytesRead);
}
}
context.Response.Flush();
context.Response.End();
}
}
else
{
context.Response.Write("Unable to retrieve content!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
private static GetObjectResponse Gets3Response(string fileName)
{
GetObjectResponse response;
if (fileName.Trim().Length == 0)
{
return null;
}
try
{
var request = new GetObjectRequest();
request.WithBucketName(BucketName).WithKey(fileName);
response = AmazonS3ClientProvider.CreateS3Client().GetObject(request);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
}
return null;
}
catch (Exception ex)
{
return null;
}
return response;
}