.Net Core 3.0 访问不带扩展名的 apple-app-site-association

在 .NET Core 中,StaticFileMiddleware 处理静态文件时,对于不带扩展名的文件(如 apple-app-site-association)需要特殊配置。你遇到的问题是因为:

  1. . 作为键值不匹配无扩展名文件 - 你配置的 {".","application/json"} 实际上是将 . 这个"扩展名"映射为 JSON 类型,而不是处理无扩展名文件。

  2. 默认行为 - StaticFileMiddleware 默认不会提供没有扩展名的文件,即使文件存在。

解决方案:

  1. 使用正确的 MIME 类型映射

    new FileExtensionContentTypeProvider
    {
        Mappings =
        {
            [""] = "application/json" // 空字符串表示无扩展名
        }
    }
    
  2. 完整解决方案

app.UseStaticFiles(new StaticFileOptions
{
    ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
    {
        { ".apk", "application/vnd.android.package-archive" },
        { "", "application/json" } // 处理无扩展名文件
    }),
    ServeUnknownFileTypes = true, // 允许提供未知类型的文件
    DefaultContentType = "application/json" // 设置默认内容类型
});
  1. 额外建议
    • 确保文件确实存在于你的 wwwroot 目录中
    • 确保文件有正确的读取权限
    • 你可能需要清除浏览器缓存进行测试
    • 考虑添加路由规则专门处理这个文件:
      app.Map("/apple-app-site-association", subApp => 
      {
          subApp.Run(async context =>
          {
              context.Response.ContentType = "application/json";
              await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "apple-app-site-association"));
          });
      });
      

这样配置后,无扩展名的 apple-app-site-association 文件应该能够被正确访问了。

默认页

public class Startup
{
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseIpRateLimiting();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseStatusCodePagesWithReExecute("/Home/Error");
        }

        app.UseRequestLogHandler();

        app.UseCorsMiddleware();

        DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
        defaultFilesOptions.DefaultFileNames.Clear();
        defaultFilesOptions.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(defaultFilesOptions);

        app.UseStaticFiles();

        app.UseStaticFiles(new StaticFileOptions
        {
            //FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
            //设置不限制content-type 该设置可以下载所有类型的文件,但是不建议这么设置,因为不安全
            //下面设置可以下载apk和nupkg类型的文件
            ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
            {
                { ".apk", "application/vnd.android.package-archive" },
                {".","application/json"}
            }),
        }); 
    }
 }
posted @ 2025-07-29 13:49  VipSoft  阅读(55)  评论(0)    收藏  举报