Tuesday, February 2, 2016

Handling 404 Error for Unknown File Extensions in ASP.NET Core 1.0

Exclusive Amazon Deals
In my previous article, I already briefed about Static Files in ASP.NET Core. Now let’s move bit further and know about how ASP.NET treats content files which are of unknown type for any browser. You might be aware that ASP.NET Core middleware serves only those content files which falls under known content types. As of now, it defines close to 400 known file content types. Now question is, how browser will 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 and browser has no information about it. 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 L
But is this message correct? If you will go back and cross check your solution explorer, that file is present as:

Now question is why such 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 file of unknown type, we have to tell browser that 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 to a file whose content type is unknown, the browser will treat it as an image and render it accordingly as shown below:

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 alsoJ. 

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 an 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.

No comments:

Post a Comment