Search code examples
c#asp.net-mvc.net-coreasp.net-core-mvcrazorengine

which class is responsible for generating response?


I'm new to Razor Engine, just have a question on generating response in ASP.NET MVC

Firstly, we know that the role of a view engine is to translate requests for views into ViewEngineResult objects, and Razor view engine implements IViewEngine

public interface IViewEngine
{
   ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage);
   ViewEngineResult GetView(string executingFilePath, string viewPath, bool isMainPage);

}

and in FindView or GetView method, the Razor engine return a ViewEngineResult object as:

// pseudo code for simplification
if view_found 
   return ViewEngineResult.Found(viewName, new RazorView(...));

the RazorView implements IView as:

public class RazorView : IView
{
   public string Path { get; }
   public virtual Task RenderAsync(ViewContext context);
}

and RenderAsync function seems to be the guy that generates response.

but .cshtml files also get compiled into C# class by Razor engine, below is n example generated C# code of index.cshtml:

public class ASPV_Views_Home_Index_cshtml : RazorPage<string[]> {
   ...
   public override async Task ExecuteAsync() {
      ...//this method also seems to generate response
   }
}

so ExecuteAsync also seems to generate response

Lastly, if we look at ViewResult object returned by action method, ViewResult implements ActionResult(implements IActionResult) as

public class ViewResult : ActionResult
{
  ...
  public override Task ExecuteResultAsync(ActionContext context); 
}

ExecuteResultAsync also seems to generate response.

so we have three candidates

1-RazorView.RenderAsync()

2-RazorPage.ExecuteAsync()

3-ViewResult.ExecuteResultAsync()

which one is the real one that generate response?


Solution

  • ExecuteResultAsync is handled differently based on the type of the result (ViewResult, PageResult, ContentResult, JsonResult, etc.). In case of ViewResult, its main responsibility is setting the HttpResponse object properties ( StatusCode, ContentType, Body, etc.).

    Internally ExecuteResultAsync calls RenderAsync which is responsible for rendering the view and its layout.

    Again, internally RenderAsync calls ExecuteAsync. ExecuteAsync is what does the actual rendering of the razor syntax.

    You can download the .NET Core repository AspNetCore and check the details of how everything is wired up -under Microsoft.AspNetCore.Mvc namespace-.