【问题标题】:which class is responsible for generating response?哪个类负责生成响应?
【发布时间】:2019-08-07 07:50:43
【问题描述】:

我是 Razor 引擎的新手,只是有一个关于在 ASP.NET MVC 中生成响应的问题

首先,我们知道视图引擎的作用是将视图请求翻译成ViewEngineResult对象,Razor视图引擎实现IViewEngine

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

}

FindViewGetView 方法中,Razor 引擎将ViewEngineResult 对象返回为:

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

RazorViewIView 实现为:

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

RenderAsync 函数似乎是产生响应的那个人。

但是 .cshtml 文件也会被 Razor 引擎编译成 C# 类,下面是 index.cshtml 生成的 C# 代码示例:

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

所以ExecuteAsync 似乎也产生了响应

最后,如果我们查看 action 方法返回的 ViewResult 对象,ViewResultActionResult(implements IActionResult) 实现为

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

ExecuteResultAsync 似乎也产生了响应。

所以我们有三个候选人

1-RazorView.RenderAsync()

2-RazorPage.ExecuteAsync()

3-ViewResult.ExecuteResultAsync()

哪一个是真正产生响应的?

【问题讨论】:

    标签: c# asp.net-mvc .net-core asp.net-core-mvc razorengine


    【解决方案1】:

    ExecuteResultAsync 的处理方式因结果类型而异(ViewResultPageResultContentResultJsonResult 等)。对于ViewResult,它的主要职责是设置HttpResponse对象属性(StatusCodeContentTypeBody等)。

    在内部ExecuteResultAsync 调用RenderAsync,它负责渲染视图及其布局。

    同样,内部RenderAsync 调用ExecuteAsyncExecuteAsync 是剃刀语法的实际呈现。

    您可以下载 .NET Core 存储库 AspNetCore 并查看所有连接方式的详细信息 - 在 Microsoft.AspNetCore.Mvc 命名空间下 -。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多