I have a specialised case where I wish to serve a straight html file from a Controller Action.
I want to serve it from a different folder other than the Views folder. The file is located in
Solution\Html\index.htm
And I want to serve it from a standard controller action. Could i use return File? And how do I do this?
I want put my two cents in. I have found this most terse and it is there already :
Check this out :
Can you read the html file in a string and return it in action? It is rendered as Html page as shown below:
Home/GetHtmlFile?file=Solution\Html\index.htm
If the destination or storage mechanism of HTML files is complicated then you can you Virtual path provider
Virtual path provider MVC sample
I extended wahid's answer to create HtmlResult
Create Html Result which extends FilePathResult
Created static method on controller
used like we return view
Hope it helps
Alternative approach if using .net core is to use a FileProvider. The files could be in a folder or embedded at compile time.
In this example we will use embedded files.
Add a folder in your project let's say assets, in it create a file myfile.html, add some basic html to the file say
Right click on the new file (assuming you are in visual studio) select properties, in the properties screen / build action, select embedded resource. It will add the file to the csproj file.
Right click on your project, edit your csproj file. Check that your property group contains the following:
If not please add it. The csproj should also contain the newly created html file as:
To read the file in your controller and pass it to the client requires a file provider which is added to the startup.cs
Edit your startup.cs make sure it includes the HostingEnvironment:
Then create a file provider and make it a service that can be injected at runtime. Create it as follows:
To serve the file go to your controller, use dependency injection to get the FileProvider, create a new service and serve the file. To do this, start with dependency injection by adding the provider to your constructor.
Then use the file provider in your service
For more info see ASP .Net Core file provider sample and the Microsoft documentation here.
If you want to render this index.htm file in the browser then you could create controller action like this:
or just by:
So lets say this action is in Home controller and some user hits http://yoursite.com/Home/GetHtml then index.htm will be rendered.
EDIT: 2 other methods
If you want to see raw html of index.htm in the browser:
If you just want to download file: