Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a file result when I don't know the content type

Tags:

asp.net-mvc

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

What is the proper way to return a file result if I only have the path to the file available?

like image 887
Jim Geurts Avatar asked Mar 30 '10 04:03

Jim Geurts


People also ask

Which action result will return a file content?

In the Index method, we have passed a string into the Content method. This Content method produces a ContentResult; this means the Index method will now return ContentResult.

Can I return action result instead of view result?

When you set Action's return type ActionResult , you can return any subtype of it e.g Json,PartialView,View,RedirectToAction.

How do I return a view from the action method?

To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “. cshtml” is not required.


1 Answers

Take the file extension, and look it up in the registry. The entry for it will have a "Content type" property.

Here's 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 );
like image 137
James Curran Avatar answered Sep 21 '22 00:09

James Curran