asp.net核心 - 如何提供没有扩展名的静态文件

Mat*_*rts 11 asp.net-core

ASP.NET Core根据文件wwwroot的mime类型提供文件夹中的文件.但是如何让它提供没有扩展名的文件呢?

例如,Apple要求您在应用中使用端点/apple-app-site-association进行某些应用集成.如果您将名为apple-app-site-association的文本文件添加到wwwroot中,则无效.

我试过的一些事情:

1)提供没有扩展时的映射:

var provider = new FileExtensionContentTypeProvider();
provider.Mappings[""] = "text/plain";
app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider
            });
Run Code Online (Sandbox Code Playgroud)

2)添加应用程序重写:

var options = new RewriteOptions()
.AddRewrite("^apple-app-site-association","/apple-app-site-association.txt", false)
Run Code Online (Sandbox Code Playgroud)

没有工作,唯一有效的是.AddRedirect我不愿意使用的东西.

sin*_*fis 22

添加替代解决方案.您必须将ServeUnknownFileTypes设置为true,然后设置默认内容类型.

        app.UseStaticFiles(new StaticFileOptions
        {
            ServeUnknownFileTypes = true,
            DefaultContentType = "text/plain"
        });
Run Code Online (Sandbox Code Playgroud)

  • 拒绝投票,因为这会增加ASP Core文档中所述的安全风险。接受的答案是在不打开所有文件类型的情况下将文件“列入白名单”的最佳方法。 (4认同)
  • 这应该是正确和最佳答案 (3认同)
  • 如果您担心安全性,您可以使用此选项使用特定的 PhysicalFileProvider 来缩小所提供文件的范围,或者将您自己的 IFileProvider 实现为 StaticFileOptions.FileProvider 属性。 (3认同)

Gab*_*uci 7

我认为你最好只为它创建一个控制器,而不是与静态文件作斗争:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace MyApp.Controllers {
    [Route("apple-app-site-association")]
    public class AppleController : Controller {
        private IHostingEnvironment _hostingEnvironment;

        public AppleController(IHostingEnvironment environment) {
            _hostingEnvironment = environment;
        }

        [HttpGet]
        public IActionResult Index() {
            return Content(System.IO.File.ReadAllText(Path.Combine(_hostingEnvironment.WebRootPath,"apple-app-site-association")), "text/plain");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这假定您的apple-app-site-association文件位于wwwroot文件夹中.

  • 如果它是愚蠢的,但是有效,那么它不是愚蠢的!:) (2认同)

小智 7

一个更简单的选择可能是在服务器上放置一个具有适当扩展名的文件,然后按如下方式使用 URL 重写。

app.UseRewriter(new RewriteOptions()
    .AddRewrite("(.*)/apple-app-site-association", "$1/apple-app-site-association.json", true));
Run Code Online (Sandbox Code Playgroud)