I believe that to follow this path you will face some problems, in any case I have some suggestions.
To return the file HTML
to the user, you can convert the string
for byte[]
and return a FileResult
as 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 binary in the Cache and use the GUID
as 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 extreme priority and that never expires, so set it up fondly.
so when calling this controller, you can check if the above binary exists in the cache and you won’t 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 that to use the MemoryCache
it is necessary to add the Assembly System.Runtime.Caching
to your project.
but if your templates are a little more complex, you can use Handlebars.NET
, in this case your html
goes gives 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 Cache.
To learn more about the syntax of Handlebars
, can look at his version’s website for JavaScript
:
HandlebarsJS
What is the purpose of this generation?
– Leonel Sanches da Silva
Gypsy the goal would be to generate billets, as the billet is per user, I can not create file by file on the server, remembering that I want to study the subject because I’m learning.
– user6901
@user6901, in this case you don’t need to implement anything new, just use a view with the Template Engine of your choice, such as Razor.
– Tobias Mesquita
Thank you Tobymosque, I’ll look into it.
– user6901