Search code examples
c#reactjsasp.net-corehttp-status-code-404applicationhost

Can't serve some file extensions from .NET Core local server even after modifying <requestFiltering> in applicationHost.config


I'm building a website and I've come across the problem of not being able to access/download some file extensions like .py, .cs. When I make a request to fetch a .cs file for example..

fetch("https://localhost:44310/userdata/texts/7/637381399366309280.cs")
        .then(resp => resp.blob())
        .then(blob => {
            success(blob)
        })
        .catch((res) => alert('oh no!'));

userdata folder is a direct child of wwwroot folder. success is a function that converts blob to text. For a .txt file (which is in the same folder as the .cs file), everything works fine and I get the exact text the .txt file contains. But for a .cs file, I get markup text - the index.html of my site. Strange thing is oh no! is not alerted. I tried with some random .cs file hosted on github and it works perfectly.

Initially, I got an outright 404. When I tried opening the link (https://localhost:44310/userdata/texts/7/637381399366309280.cs) in the browser, I get the page below: enter image description here

I did some research and located the applicationHost.config and removed all the filtered extensions such that it looked like this:

<requestFiltering>
   <fileExtensions allowUnlisted="true" applyToWebDAV="false">
          <!--empty-->
   </fileExtensions>
   ....
</requestFiltering>

Now I don't get a 404 anymore. But success(blob) returns markup text - the index.html of my site. (I use Reactjs and I've noticed this happens when something goes wrong with the fetch.) When I try opening the url in a new tab, I don't get the requestFiltering error page anymore. Instead, the home page of the site loads.

So I'm really confused. I don't get a 404, but I don't seem to be getting the file either. Modifying the requestFiltering changed something, but it seems there's something else I need to do. Please help.


Solution

  • Turns out that in addition to editing the <requestFiltering> in the applicationHost.config file, I also have to ServeUnknownFileTypes in the startUp class.

    app.UseStaticFiles(new StaticFileOptions
    {
       ServeUnknownFileTypes = true,
       DefaultContentType = "text/plain"
    });
    

    Check out this answer to learn more.