【问题标题】:ASP.NET Core - Download .exe returns 404 errorASP.NET Core - 下载 .exe 返回 404 错误
【发布时间】:2017-03-16 18:53:16
【问题描述】:

我有一个 ASP.NET 核心 MVC 应用程序,在 wwwroot 文件夹中,我添加了另一个名为“Shaun”的文件夹,并在该文件夹中放置了一个 exe 以尝试下载:

现在,如果我导航到:http://localhost:PORT/Shaun/chromesetup.exe,我会收到 404 错误。我尝试在下面添加处理程序,但这不起作用。

 <add name="Client exe" path="*.exe" verb="*" modules="StaticFileModule" resourceType="File" />

额外信息:我需要这样做的原因是因为我有一个连接到该网站的客户端应用程序,该客户端应用程序使用 ClickOnce 打包并放入网站的 wwwroot 中,这以前使用 MVC(pre核心)并且仍然可以,但没有核心。

我该如何解决这个问题?

【问题讨论】:

  • 这可能是因为StaticFileHandler中间件不允许文件扩展名。 (Dotnet核心本身就有StaticFileHandlerMiddleware)
  • @JoelHarkes 如何让它允许?
  • @Smity 我为你提供了答案

标签: c# asp.net asp.net-mvc download asp.net-core


【解决方案1】:

尝试以下方法并告诉我它是否有效:

app.UseStaticFiles(new StaticFileOptions
{
    ServeUnknownFileTypes = true, //allow unkown file types also to be served
    DefaultContentType = "Whatver you want eg: plain/text" //content type to returned if fileType is not known.
}

您可以查看StaticFileMiddleware 的源代码,了解它是如何处理静态文件的。

默认情况下,FileExtensionContentTypeProvider 用于根据文件扩展名检查需要在 Http 响应标头中返回的 ContentType。 exe 不在此列表中。

所以另一种选择是将 Exe 添加到此列表中:

var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".exe", "application/vnd.microsoft.portable-executable"); //file ext, ContentType
app.UseStaticFiles(new StaticFileOptions
{
    ContentTypeProvider = provider
});

【讨论】:

  • 你的第一个代码可以正常工作,现在就去测试第二个sn-p!你知道它们之间的区别吗?
  • @Smithy 如果您阅读我的文字,它应该提供原因。首先返回默认的内容类型
  • 是的,第二个 sn-p 也可以:D 我认为 ServerUnknownFileTypes 会返回任何内容,并且将 .exe 添加到列表中更安全?
  • 非常感谢!
【解决方案2】:

为了提供静态文件(.exe 文件是一种静态文件类型),您必须配置中间件以将静态文件添加到管道中。静态文件中间件可以通过在项目中添加对 Microsoft.AspNetCore.StaticFiles 包的依赖,然后从 Startup.Configure 调用 UseStaticFiles 扩展方法来配置:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 2011-08-03
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2023-02-19
    相关资源
    最近更新 更多