How to return the result of a file when I do not know the type of content

I have an asp.net mvc action that returns the result of a file. Behind the scenes, it simply returns a file from the directory. FilePathResult requires a content type, but I don't know that.

What is the correct way to return the result of a file if I only have the path to the file?

+4
source share
1 answer

Take the file extension and see it in the registry. The record for it will have the "Content Type" property.

Here is a complete example of returning a FilePathResult from a controller action:

string filePysicalPath, fileName; //these need to be set to your values. var reg = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey( Path.GetExtension( filename ).ToLower() ); string contentType = "application/unknown"; if ( reg != null ) { string registryContentType = reg.GetValue( "Content Type" ) as string; if ( !String.IsNullOrWhiteSpace( registryContentType ) ) { contentType = registryContentType; } } return File( filePysicalPath, contentType, filename ); 
+9
source

Source: https://habr.com/ru/post/1305507/


All Articles