【问题标题】:IHttpHandler doesn't load image after deployed to web serverIHttpHandler 部署到 Web 服务器后不加载图像
【发布时间】:2013-06-13 11:19:39
【问题描述】:

我现在在将我的网站部署到共享 Windows 主机时遇到问题。

我目前正在使用 hostgator 托管它。

问题是,我应该返回图像文件的 ThumbnailHandler 在项目部署到网络服务器后停止工作。它在本地IIS虚拟文件夹和vs2010调试中正常工作。

例如-

http://www.myweb.com/imageHandler.ashx?i=0 - 错误

http://www.myweb.com/imageHandler.ashx - 错误

http://www.myweb.com/image-handler?i=0 - (使用 IRouteHandler 路由) 错误

http://www.myweb.com/img/theimage.jpg - 好的!

不抛出异常。如果我打开网址,它会返回“图像(路径)无法显示,因为它包含错误”。

ThumbnailHandler.ashx

public void ProcessRequest(HttpContext context) {
    context.Response.Flush();
    Size maxSize = new Size(98, 98);
    byte[] buffer = Imaging.GetImage(context.Server.MapPath("~/img/noimage98.png"), maxSize).GetBytes(System.Drawing.Imaging.ImageFormat.Jpeg);
    try {
        Int32 index = GetImageIndex(context);
        maxSize = GetMaxSize(context);
        if (index < 0 || maxSize == null)
            throw new Exception("Index size is not specified.");
        String authToken = GetAuthenticationToken(context);
        DirectoryInfo directoryInfo = AdvertisementDirectory.GetDirectoryInfo(authToken);
        List<FileInfo> fileInfos = AdvertisementDirectory.GetImageFileInfoList(directoryInfo);
        using (System.Drawing.Image thumbnailImage = Imaging.GetImage(fileInfos[index].FullName, maxSize)) {
            buffer = thumbnailImage.GetBytes(System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
    catch (Exception ex) {
        throw ex;
    }
    finally {
        context.Response.ContentType = "image/jpeg";
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
        context.Response.Flush();
        context.Response.Close();
        context.ApplicationInstance.CompleteRequest();
    }
}
public bool IsReusable { get { return false; } }

web.config

<globalization requestEncoding="iso-8859-1" responseEncoding="iso-8859-1" fileEncoding="utf-8" culture="en-US" uiCulture="en-US"/>

<pages buffer="true" clientIDMode="Static" controlRenderingCompatibilityVersion="4.0" enableViewStateMac="true" validateRequest="true" enableEventValidation="true" enableSessionState="true" viewStateEncryptionMode="Auto" >
  <controls>
    <add tagPrefix="ATK" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
  </controls>
</pages>

<httpHandlers>
  <add verb="*" path="*.ashx" type="Tradepost.ThumbnailHandler, Tradepost"/>
</httpHandlers>

<httpRuntime executionTimeout="600" maxRequestLength="40000" maxUrlLength="260" maxQueryStringLength="2048" requestLengthDiskThreshold="80" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="5000" enableKernelOutputCache="true" enableVersionHeader="true" requireRootedSaveAsPath="true" enable="true" shutdownTimeout="90" delayNotificationTimeout="5" waitChangeNotification="0" maxWaitChangeNotification="0" enableHeaderChecking="true" sendCacheControlHeader="true" apartmentThreading="false" requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

以前有人经历过吗?我还尝试检查文件夹权限安全设置。任何帮助表示赞赏,在此先感谢。

注意:任何文件夹中的任何图像都会出现这种情况。

【问题讨论】:

    标签: c# asp.net shared-hosting


    【解决方案1】:

    在 img 文件夹中加载图像时,img 文件夹无法读取/写入文件。 因此,首先要授予对 img 文件夹的所有访问权限以读取和写入图像。

    或者您尝试提供图像的完整路径,因为有时客户端服务器具有不同的根路径所以Server.MapPath

    没有得到图片的确切路径。

    你可以尝试在 web.config appsetting 控件中定义起始域名的路径,然后这个 在处理程序中使用路径来获取图像的路径。

    <appSettings>
            <add key="ProjectName" value="/www.myweb.com"/>
    </appSettings>
    

    在处理程序页面中使用

    string ProjectName = System.Configuration.ConfigurationManager.AppSettings["ProjectName"].ToString().Trim();
    byte[] buffer = Imaging.GetImage(ProjectName+"/img/noimage98.png", maxSize).GetBytes(System.Drawing.Imaging.ImageFormat.Jpeg);
    

    【讨论】:

    • 正如我所说,我已经三次检查了相应的文件夹权限并允许每个用户访问它。在完整路径图像的情况下,因为它是共享的 Windows 托管。我认为我无法访问根路径。但是,我没有尝试从“url”获取图像,我会尝试更新你。谢谢:)
    • 嘿,使用来自 Uri 的流确实有效。谢谢 :)。但由于某种原因,我仍然需要使用 MapPath 方法。对我还有什么建议吗?
    【解决方案2】:

    好的,我发现了问题。 从字面上看,我的主机提供商不支持完全信任策略,所以我不得不将其更改为中等信任。即使我在 web.config 上设置了完全信任,它也会将其更改回中等信任或显示错误。

    所以,错误发生在我的“GetImage”函数上,它是

    public static System.Drawing.Image GetImage(String fileName, System.Drawing.Size maxSize) {
        System.Drawing.Image result = null;
        try {
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                using (System.Drawing.Image img = System.Drawing.Image.FromStream(fs, true, false)) {
                    Size sz = GetProportionalSize(maxSize, img.Size);
                    result = img.GetThumbnailImage(sz.Width, sz.Height, null, IntPtr.Zero);
                    }
                fs.Close();
            }
        }
        catch (Exception ex) {
            throw ex;
        }
        return result;
    }
    

    using (FileStream fs = File.OpenRead(fileName)) {
        using (StreamReader sr = new StreamReader(fs)) {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(sr.BaseStream, true, false)) {
                System.Drawing.Size sz = GetProportionalSize(maxSize, img.Size);
                result = img.GetThumbnailImage(sz.Width, sz.Height, null, IntPtr.Zero);
            }
            sr.Close();
        }
        fs.Close();
    }
    

    然后抛出...

    System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer
    

    但是, 我还是不知道WHY下面的代码WORKS

    using (System.Drawing.Image img = System.Drawing.Image.FromFile(fileName)) {
        System.Drawing.Size sz = GetProportionalSize(maxSize, img.Size);
        result = img.GetThumbnailImage(sz.Width, sz.Height, null, IntPtr.Zero);
    }
    

    我已经在我的 web.config

    中使用我的主机提供商和本地 IIS 对其进行了测试
    <trust level="Medium" originUrl=""/>
    

    无论如何,它现在可以工作了。 我仍然没有合适的时间来找出为什么 Stream 类型对象的行为与 Image.FromFile 不同,因为我知道文件的这两个仍然是流。 如果我发现一些有趣的东西,我会发布更多更新。

    干杯。

    【讨论】:

    • 所以,如果我使用FromFile,而不是使用FromStream,这个信任问题就会得到解决。
    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    相关资源
    最近更新 更多