K
K
Kolejium2018-12-21 17:42:32
ASP.NET
Kolejium, 2018-12-21 17:42:32

WebApi + Razor how should it work?

Hey!
For quite a long time I have been writing various services and micro services in the connection Architecture -> WebApi -> React / Angular (short face).
Given a task, you need to use WebApi + Razor. I have been using Razor for a very long time, when I only studied MVC. How can I combine it?
IMPORTANT! WebApi + Razor must be in the same assembly. Well, in theory, Razor should be used somehow efficiently.
Details:
I have API controllers - they work great. Ninject is connected to Asp.Net Core (Standard DI has been replaced).
The API controller receives the service from the business logic. Using the service in RazorPage also violates the Dry principle.
Do not really have to vyyuzivat HttpClient???
It's just that if I use only JS / jQuery, it's not a variant.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2018-12-21
@kttotto

Mvc generates html based on cshtml files and gives it to the client. You can do the same with your hands in a WebApi application using RazorEngine.Templating.
Here is a link to a similar question .
And I am attaching a truncated example that we used to generate reports, I think you will figure it out.

spoiler
public class RazorTemplateGenerator
{
  public void SetupReportTemplating(string baseDirectory = null)
  {
    var cfg = new TemplateServiceConfiguration
    {
      Debug = true
    };

    Engine.Razor = RazorEngineService.Create(cfg);

    var folder = Path.Combine(baseDirectory ?? System.AppDomain.CurrentDomain.BaseDirectory, "Pages","PageTemplates");
    var templates = Directory.GetFiles(folder, "*.cshtml");
    foreach (var fName in templates)
    {
      var info = new FileInfo(fName);
      var tName = Path.GetFileNameWithoutExtension(info.Name);
      var template = File.ReadAllText(fName);
      var src = new LoadedTemplateSource(template, fName.Replace(@"\bin",String.Empty));
      Engine.Razor.AddTemplate(tName, src);
    }
  }

  public void CheckCompile(string name)
  {
    Engine.Razor.Compile(name);
  }

  public string RenderPage(string viewName, object model)
  {
    return Engine.Razor.RunCompile(viewName, model.GetType(), model);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question