Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
Render Razor views from string

I have looked for similar questions but have not managed to build a solution yet.

Basically what I need is to render views from strings in memory.

Example:

    public IActionResult Test()
    {
        var model = new MyModel
        {
            Name = "Joe"
        };

        var cshtml = "<h1> Hello @Model.Name </h1>";

        var myView = MyAwesomeEngine.CreateView(cshtml, model);

        return View(myView)
        //or
        return myView
    }

Is this possible? I have tried RazorViewEngine inheritance without success, what would be the correct way to render views from string without looking for files in view paths?

I am using aspnetcore 1.1

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

As Legends suggested using IFileProvider method worked correctly!

Using the example of this link I was able to do it (without the database)

This was my test IFileInfo implementation:

public class MemoryFileInfo : IFileInfo
    {
        private byte[] _testContent = Encoding.ASCII.GetBytes(@"@model TestModel
            <p>@Model.Name</p>");

        private string _viewName;
        public bool Exists { get
            {
                return _viewName.Equals("/Views/Home/TestView.cshtml");
            }
        }

        public MemoryFileInfo(string name)
        {
            _viewName = name;
        }

        public long Length => _testContent.Length;

        public string PhysicalPath => null;

        public string Name => _viewName;

        public DateTimeOffset LastModified => DateTimeOffset.Now;

        public bool IsDirectory => false;

        public Stream CreateReadStream()
        {
            return new MemoryStream(_testContent);
        }
    }

This is another great solution RazorEngine but is has no support for netcoreapp1.1 yet

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda