adoconnection / RazorEngineCore

.NET6 Razor Template Engine
MIT License
565 stars 84 forks source link

Support for binary content #98

Open lsadehaan opened 2 years ago

lsadehaan commented 2 years ago

Hi, first of all I want to congratulate you on a very nice, clean and concise wrapper around the Razor engine. I had a look at a few other options and this one is by far the cleanest in my opinion. I do however have a small improvement to propose.

I have what is probably a very specific use-case where I am going to use Razor to generate files of various different types - probably none or very few of which will actually be HTML.

A small subset of these will actually contain a mixture of text and binary content.

Unfortunately the current API for building the response is based around the string return type which makes it near impossible to handle binary data (at least reliably). Since I'll be writing to files with ASCII (UTF8) encoding the C# string class being Unicode (UTF16) also adds additional overhead, with my input data being converted from UTF8 binary stream to UTF16 strings and then back to UTF8 in the file.

Anyway, all of these issues are easily worked around by changing the implementation to have a templated output parameter to the Result method instead of just the fixed string. Unfortunately it does also result in almost all classes and interfaces requiring this additional template parameter and does make the internal code less easy to follow as a result, but not really in any major sense. And the added complexity can be pretty much hidden from the end user.

I have done a proof of concept implementation of this change and modified the Example project to use a very simple version of what I need and it works very nicely.

I will submit a pull request with this code for your review - it will probably require some cleaning up to be added to the code base in a backwards compatible manner.

adoconnection commented 2 years ago

Hi, thank you very much for your words, and code, you cant imagine how inspiring it is. I have busy days right now, so it will take me a while to deep dive into binary support. Looks interesting.

just in case, feel free to ping me