Handling 404 Error For Unknown File Extensions In ASP.NET Core 1.0

In my previous article, I already briefed you about Static Files in ASP.NET Core. Now let’s move bit further and learn about how ASP.NET treats content files which are of an unknown type for any browser. You might be aware that ASP.NET Core middleware serves only those content files which fall under known content types. As of now, it defines close to 400 known file content types. Now the question is, howwill the browser respond to unknown content type files? Let’s understand it better with an example.

I’m having an image file named SampleData with extension as .shweta. Here shweta is my custom extension andthe browser has no information about it. The browser has no idea about how to render this type of file. Please note, this is a static resource placed on wwwroot and has to be served to client. Now quickly open SampleData.shweta in browser and see what happens.

Uhh! This is HTTP 404 Not Found :( .
 
But is this message correct? If you will go back and cross check your solution explorer, that file is present as:



























Now the question is why is there such a discrepancy? Straight forward answer would be – ASP.NET middleware is not able to serve this unknown file type.

Serving unknown content type

In order to serve files of an unknown type, we have to tell the browser which type of file is this. Fortunately, ASP.NET provides us with two useful properties named ServeUnknownFileTypes and DefaultContentType which will do this task for us.
 







Now if the user glances at a file whose content type is unknown, the browser will treat it as an image and render it accordingly as shown below:










The next interesting question is, what if there are multiple types of files having an unknown to ASP.NET? No worries, ASP.NET Core has solution for that also. 

Serving multiple unknown content types

It provides a class named FileExtensionContentTypeProvider. Hence any custom content type has to be first added in a collection of this class with proper mapping of extension MIME type. Below is the sample code for achieving this:







More information about FileExtensionContentTypeProvider class is given here at github and more information about application/x-msdownload is given here.

Hope you enjoyed learning unknown content types in ASP.NET Core.

Up Next
    Ebook Download
    View all
    Learn
    View all