Search code examples
asp.net-core

asp.net core - How to serve static file with no extension


ASP.NET Core hapily serves up files from the wwwroot folder based on the mime type of the file. But how do I get it serve up a file with no extension?

As an example, Apple require that you have an endpoint in your app /apple-app-site-association for some app-intergration. If you add a text file called apple-app-site-association into your wwwroot it won't work.

Some things I've tried:

1) Provide a mapping for when there's no extension:

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

2) Adding an app rewrite:

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

Neither work, the only thing that does work is a .AddRedirect which I'd rather not use if possible.


Solution

  • Rather than fighting with static files, I think you'd be better off just creating a controller for it:

    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 async Task<IActionResult> Index() {
                return Content(
                    await File.ReadAllTextAsync(Path.Combine(_hostingEnvironment.WebRootPath, "apple-app-site-association")),
                    "text/plain"
                );
            }
        }
    }
    

    This assumes your apple-app-site-association file is in your wwwroot folder.