【问题标题】:ASP.NET MVC Uploads and Downloads, Using IIS to control MIME Types?ASP.NET MVC 上传和下载,使用 IIS 控制 MIME 类型?
【发布时间】:2014-10-30 22:13:45
【问题描述】:

简而言之,有没有办法让 MVC Upload ActionResult & Download FileResult 遵守 web.config 的禁止 MIME 类型?

我看到一些解决方案主要集中在 ActionResult 中的 MIME 类型的硬编码,方法是在上传时检查 HttpPostedFileBase 并在下载时提供 MIME 类型,但我正在寻找一种更优雅的方法。硬编码,甚至用 appsettings 重新发明轮子似乎很愚蠢。

我已将以下内容放入 web.config 无济于事:

<httpHandlers>
  <add verb="*" path="*.exe" type="System.Web.HttpForbiddenHandler" />    
</httpHandlers>

MVC 只是不尊重 IIS 在 MIME 类型上的配置,而是自行其是,令人沮丧。有谁知道使用 config 通过 ASP.NET MVC 完成此任务的更好方法?否则,我可能会求助于带有 appsettings 的操作过滤器来控制它,或类似的。

下载代码,只是为了展示提供文件的方法:

    /// <summary>
    /// Downloads the document.
    /// </summary>
    /// <param name="documentId">The document identifier.</param>
    /// <returns></returns>
    public ActionResult DownloadDocument(int documentId)
    {
        ActionResult actionResult = null;
        InternalClient internalClient = null;
        Document document = null;
        ContentDisposition contentDisposition = null;
        try
        {
            internalClient = new InternalClient();
            document = internalClient.GetDocument(documentId);

            contentDisposition = new ContentDisposition
            {
                FileName = document.FileName,
                Inline = false,
            };

            Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
            actionResult = File(document.FileBytes, document.ContentType);
        }
        catch (Exception exception)
        {
            exception.Log();
        }
        finally
        {
            internalClient.TryDispose();
        }

        return actionResult;
    }

【问题讨论】:

  • 在 System.webServer->handlers 上尝试相同的操作,这就是我拥有文件扩展处理程序的地方。
  • 我只是没有成功,很遗憾。感谢您的提示。

标签: c# asp.net-mvc file-upload web-config mime-types


【解决方案1】:

这是一个疯狂的猜测,但既然你提到了 MVC,我猜你可能正在运行 IIS7+。在这种情况下,httpHandlers 无关紧要,因为它们仅适用于 IIS6(或 IIS7+ 经典模式)。

要阻止 IIS7+ 提供具有特定扩展名的文件,请尝试以下操作:

<system.webServer>
    <staticContent>
        <remove fileExtension=".exe"/>
    </staticContent>
</system.webServer>

这将导致网站返回404.3 错误,如下所示:

要使其返回403,请使用此(已验证)

<system.webServer>
    <handlers>
        <add name="ExeFile" verb="*" path="*.exe" type="System.Web.HttpForbiddenHandler"/>
    </handlers>
</system.webServer>

【讨论】:

  • 只有exe 有问题吗?你能尝试一些其他的扩展,比如jpg吗?这会让你知道是否有其他东西在干扰/覆盖。
  • 还要确保你有这个:&lt;modules runAllManagedModulesForAllRequests="true" /&gt;。没有这个,IIS 将处理它,你的应用程序将没有机会做任何事情。
  • 对 runAllManagedModulesForAllRequests 大喊大叫,这让我忘记了,但它设置为 true。看起来我最终会在这一点上编写一个动作过滤器。糟透了……谢谢你的想法。
  • P.S.如果我遇到配置修复,我会更新这个 Q。
  • 给你赏金作为你时间的微不足道的象征。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多