I believe that to follow this path you will face some problems, in any case I have some suggestions.
To return the HTML
file to the user, you can convert string
to byte[]
and return FileResult
to mine-type
text/html
:
public FileResult Index()
{
var model = new
{
guid = Guid.NewGuid(),
nome = "Toby Mosque"
};
var html = $@"
<div>
<div>
<label>
GUID:
<input id='guid' type='text' value='{model.guid}' />
</label>
</div>
<div>
<label>
Nome:
<input id='nome' type='text' value='{model.nome}' />
</label>
</div>
</div>
";
var binary = Encoding.UTF8.GetBytes(html);
return File(binary, "text/html");
}
Note that in our example above the model has a unique identifier, so we can store the file's binary in the cache and use GUID
as a key.
MemoryCache.Default.Add(model.guid.ToString(), binary, new CacheItemPolicy
{
Priority = CacheItemPriority.NotRemovable,
AbsoluteExpiration = MemoryCache.InfiniteAbsoluteExpiration,
SlidingExpiration = MemoryCache.NoSlidingExpiration
});
Of course, in a production environment it is not desirable to have a Cache with an extreme priority that never expires, so configure it with care.
Then when calling this controller, you can check if the above binary exists in the cache and you will not need to create it again.
var binary = default(byte[]);
if (MemoryCache.Default.Contains(model.guid.ToString()))
{
binary = MemoryCache.Default.Get(model.guid.ToString()) as byte[];
}
else
{
var html = string.Empty;
/* Logica de montagem do HTML aqui */
binary = Encoding.UTF8.GetBytes(html);
}
return File(binary, "text/html");
Remembering to use MemoryCache
you must add the Assembly System.Runtime.Caching
to your project.
But if your templates are a bit more complex, you can use Handlebars.NET
, in this if its html
will give rise to a Function<string, object>
.
using (var reader = new StringReader(html))
{
var hbTemplate = Handlebars.Compile(reader);
var stream = hbTemplate.template(model);
return File.Stream(stream, "text/html");
}
In this case, it is desirable that you keep your templates
compiled in the Cache.
To learn more about the syntax of Handlebars
, you can look at his version site for JavaScript
:
HandlebarsJS