gpt4 book ai didi

c# - ASP.NET MVC 上传和下载,使用 IIS 控制 MIME 类型?

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:20 26 4
gpt4 key购买 nike

简而言之,有没有办法让 MVC 上传 ActionResult 和下载 FileResult 遵守 web.config 的禁止 MIME 类型?

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

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

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

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

下载代码,简单地展示提供文件的方法:

    /// <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;
}

最佳答案

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

要阻止 IIS7+ 提供具有特定扩展名的文件,试试这个:

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

这将导致站点返回 404.3 错误,如下所示: enter image description here

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

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

enter image description here

关于c# - ASP.NET MVC 上传和下载,使用 IIS 控制 MIME 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com