[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

黄舟
풀어 주다: 2016-12-30 16:07:38
원래의
1298명이 탐색했습니다.

[ASP.NET
MVC Mavericks Road] 10 - 컨트롤러 및 액션(2)

이전 기사에 이어 이번 기사에서는 Things를 포함하여 컨트롤러와 액션의 고급 기능 중 일부를 소개합니다. 컨트롤러 팩토리, 액션 호출자 및 비동기 컨트롤러와 같습니다.

이 글의 목차


시작: 예제 준비

글을 시작하기 전에 먼저 요청이 어떻게 전송되는지 이해합시다. 다음 그림 이후에 결과를 반환하는 과정을 이해해 보세요.

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

이 글의 초점은 컨트롤러 팩토리와 액션 호출자입니다. 이름에서 알 수 있듯이 컨트롤러 팩토리는 요청을 처리하는 컨트롤러 인스턴스를 만드는 데 사용되며, 액션 호출자는 Action 메서드를 찾고 호출하는 데 사용됩니다. MVC 프레임워크는 두 가지 모두에 대한 기본 구현을 제공하며 이를 사용자 정의할 수도 있습니다.

먼저 이 글에서 시연할 예시를 준비하고, 당분간 생각할 수 있는 모든 뷰, 컨트롤러, 액션을 만들어 보겠습니다. 새로운 빈 MVC 애플리케이션을 생성하고 Models 폴더에 Result라는 모델을 추가합니다. 코드는 다음과 같습니다.

namespace MvcApplication2.Models {
    public class Result {
        public string ControllerName { get; set; }
        public string ActionName { get; set; }
    }
}
로그인 후 복사

/Views/Shared 폴더 아래에 Result.cshtml이라는 뷰를 추가합니다(사용하지 마세요) 레이아웃), 다음 코드를 추가합니다.

...
<body>
    <div>Controller: @Model.ControllerName</div> 
    <div>Action: @Model.ActionName</div> 
</body>
로그인 후 복사

이 문서의 모든 Action 메서드는 실행된 컨트롤러 이름과 Action 이름을 표시하기 위해 이 동일한 뷰를 사용합니다.

그런 다음 Product라는 컨트롤러를 생성합니다. 코드는 다음과 같습니다.

public class ProductController : Controller {
        
    public ViewResult Index() {
        return View("Result", new Result {
            ControllerName = "Product",
            ActionName = "Index"
        });
    }

    public ViewResult List() {
        return View("Result", new Result {
            ControllerName = "Product",
            ActionName = "List"
        });
    }
}
로그인 후 복사

계속해서 Customer라는 컨트롤러를 추가합니다. 코드는 다음과 같습니다.

public class CustomerController : Controller {
        
    public ViewResult Index() {
        return View("Result", new Result {
            ControllerName = "Customer",
            ActionName = "Index"
        });
    }

    public ViewResult List() {
        return View("Result", new Result {
            ControllerName = "Customer",
            ActionName = "List"
        });
    }
}
로그인 후 복사

준비 작업이 완료되었으니 본론으로 들어가겠습니다.


Customized Controller Factory

Controller Factory는 이름에서 알 수 있듯이 컨트롤러 인스턴스가 생성되는 곳입니다. Controller Factory의 작동 방식을 더 잘 이해하려면 가장 좋은 방법은 사용자 정의 공장을 직접 구현하는 것입니다. 물론 실제 프로젝트에서는 직접 구현하는 경우가 거의 없으며 일반적으로 내장된 것을 사용하는 것으로 충분합니다. 컨트롤러 팩토리를 사용자 정의하려면 IControllerFactory 인터페이스를 구현해야 합니다.

using System.Web.Routing; 
using System.Web.SessionState;

namespace System.Web.Mvc { 
    public interface IControllerFactory { 
        IController CreateController(RequestContext requestContext, string controllerName); 
        SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName); 
        void ReleaseController(IController controller); 
    } 
}
로그인 후 복사

Infrastructure라는 폴더를 만들고 이 폴더에 CustomControllerFactory라는 클래스 파일을 만듭니다. 클래스에서 IControllerFactory 인터페이스의 각 메서드를 간단히 구현하겠습니다. 코드는 다음과 같습니다.

using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using MvcApplication2.Controllers;

namespace MvcApplication2.Infrastructure {
    public class CustomControllerFactory : IControllerFactory {

        public IController CreateController(RequestContext requestContext, string controllerName) {
            Type targetType = null;
            switch (controllerName) {
                case "Product":
                    targetType = typeof(ProductController);
                    break;
                case "Customer":
                    targetType = typeof(CustomerController);
                    break;
                default:
                    requestContext.RouteData.Values["controller"] = "Product";
                    targetType = typeof(ProductController);
                    break;
            }
            return targetType == null ? null : (IController)DependencyResolver.Current.GetService(targetType);
        }

        public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName) {
            return SessionStateBehavior.Default;
        }

        public void ReleaseController(IController controller) {
            IDisposable disposable = controller as IDisposable;
            if (disposable != null) {
                disposable.Dispose();
            }
        }
    }
}
로그인 후 복사

먼저 이 클래스를 분석해 보겠습니다.

여기서 가장 중요한 메소드는 MVC 프레임워크가 요청을 처리하기 위해 컨트롤러가 필요할 때 호출되는 CreateController입니다. 여기에는 두 개의 매개변수가 있습니다. 하나는 요청 관련 정보를 얻을 수 있는 RequestContext 객체이고, 두 번째 매개변수는 문자열 유형 컨트롤러 이름이며 해당 값은 URL에서 가져옵니다. 여기서는 두 개의 Controller만 만들었으므로 CreateController 메서드에 컨트롤러 이름을 하드 코딩했습니다. CreateController 메서드의 목적은 Controller 인스턴스를 만드는 것입니다.

맞춤형 컨트롤러 팩토리에서는 스위치 문의 기본 노드와 같이 시스템의 기본 동작을 마음대로 변경할 수 있습니다.

requestContext.RouteData.Values["controller"] = "Product";
로그인 후 복사


실행하는 컨트롤러가 사용자가 요청한 컨트롤러가 되지 않도록 경로의 컨트롤러 값을 Product로 변경합니다.

이 시리즈 [ASP.NET

MVC Mavericks Road] 05 - Ninject 사용 문서에서는 Ninject를 사용하여 컨트롤러 팩토리를 만드는 예도 설명합니다. .Get(controllerType) 메소드는 Controller 인스턴스를 생성하는 데 사용됩니다. 여기서는 MVC 프레임워크에서 제공하는 종속성Resolver 클래스를 사용하여 다음을 생성합니다.

return targetType == null ? null : (IController)DependencyResolver.Current.GetService(targetType);
로그인 후 복사


静态的 DependencyResolver.Current 属性返回一个 IDependencyResolver 接口的实现,这个实现中定义了 GetService 方法,它根据 System.Type 对象(targetType)参数自动为我们创建 targetType 实例,和使用Ninject类似。

最后来看看实现 IControllerFactory 接口的另外两个方法。

GetControllerSessionBehavior 方法,告诉MVC框架是否保留Session数据,这点放在文章后面讲。

ReleaseController 方法,当controller对象不再需要时被调用,这里我们判断controller对象是否实现了IDisposable接口,实现了则调用 Dispose 方法来释放资源。

CustomControllerFactory 类分析完了。和 [ASP.NET

MVC 小牛之路]05 - 使用 Ninject 讲的示例一样,要使用自定义的Controller Factory还需要在 Global.asax.cs 文件的 Application_Start 方法中对自定义的 CustomControllerFactory 类进注册,如下:

protected void Application_Start() {
    ...
    ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
}
로그인 후 복사

运行程序,应用程序根据路由设置的默认值显示如下:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

你可以定位到任意 /xxx/xxx 格式的URL来验证我们自定的 Controller Factory 的工作。


使用内置的 Controller Factory

为了帮助理解Controller Factory是如何工作,我们通过实现IControllerFactory接口自定义了一个Controller Factory。在实际的项目中,我们一般不会这么做,大多数情况我们使用内置的Controller Factory,叫 DefaultControllerFactory。当它从路由系统接收到一个请求后,从路由实例中解析出 controller 的名称,然后根据名称找到 controller 类,这个类必须满足下面几个标准:

必须是public。
必须是具体的类(非抽象类)。
没有泛型参数。
类的名称必须以Controller结尾。
类必须(间接或直接)实现IController接口。

DefaultControllerFactory类维护了一个满足以上标准的类的列表,这样当每次接收到一个请求时不需要再去搜索一遍。当它找到了合适的 controller 类,则使用Controller Activator(一会介绍)来创建Controller 类的实例。它内部是通过 DependencyResolver 类进行依赖解析创建 controller 实例的,和使用Ninject是类似的原理。

你可以通过继承 DefaultControllerFactory 类重写其中默认的方法来自定义创建 controller 的过程,下面是三个可以被重写的方法:

GetControllerType,返回Type类型,为请求匹配对应的 controller 类,用上面定义的标准来筛选 controller 类也是在这里执行的。
GetControllerInstance,返回是IController类型,作用是根据指定 controller 的类型创建类型的实例。
CreateController 方法,返回是 IController 类型,它是 IControllerFactory 接口的 CreateController 方法的实现。默认情况下,它调用 GetControllerType 方法来决定哪个类需要被实例化,然后把controller 类型传递给GetControllerInstance。

重写 GetControllerInstance 方法,可以实现对创建 controller 实例的过程进行控制,最常见的是进行依赖注入。

在本系列的 [ASP.NET
MVC 小牛之路]05 - 使用 Ninject 文章中的示例就是一个对 GetControllerInstance 方法进行重写的完整示例,在这就不重复演示了。

现在我们知道 DefaultControllerFactory 通过 GetControllerType 方法拿到 controller 的类型后,它把类型传递给 GetControllerInstance 方法以获取 controller 的实例。那么,GetControllerInstance 又是如何来获取实例的呢?这就需要讲到另外一个 controller 中的角色了,它就是下面讲的:Controller Activator。


Controller 的激活

当 DefaultControllerFactory 类接收到一个 controller 实例的请求时,在 DefaultControllerFactory 类内部通过 GetControllerType 方法来获得 controller 的类型,然后把这个类型传递给 GetControllerInstance 方法以获得 controller 的实例。

所以在 GetControllerInstance 方法中就需要有某个东西来创建 controller 实例,这个创建的过程就是 controller 被激活的过程。

默认情况下 MVC 使用 DefaultControllerActivator 类来做 controller 的激活工作,它实现了 IControllerActivator 接口,该接口定义如下:

public interface IControllerActivator { 
    IController Create(RequestContext requestContext, Type controllerType); 
}
로그인 후 복사


该接口仅含有一个 Create 方法,RequestContext 对象参数用来获取请求相关的信息,Type 类型参数指定了要被实例化的类型。DefaultControllerActivator 类中整个 controller 的激活过程就在它的 Create 方法里面。下面我们通过实现这个接口来自定义一个简单的 Controller Activator:

public class CustomControllerActivator : IControllerActivator {
    public IController Create(RequestContext requestContext, Type controllerType) {
        if (controllerType == typeof(ProductController)) {
            controllerType = typeof(CustomerController);
        }
        return (IController)DependencyResolver.Current.GetService(controllerType);
    }
}
로그인 후 복사

这个 CustomControllerActivator 非常简单,如果请求的是 ProductController 则我们给它创建 CustomerController 的实例。为了使用这个自定的 Activator,需要在 Global.asax 文件中的 Application_Start 方法中注册 Controller Factory 时给 Factory 的构造函数传递我们的这个 Activator 的实例,如下:

protected void Application_Start() { 
    ...
    ControllerBuilder.Current.SetControllerFactory(new DefaultControllerFactory(new CustomControllerActivator())); 
}
로그인 후 복사

运行程序,把URL定位到 /Product ,本来路由将指定到 Product controller, 然后 DefaultControllerFactory 类将请求 Activator 创建一个 ProductController 实例。但我们注册了自义的 Controller Activator,在这个自定义的 Activator 创建 Controller 实例的的时候,我们做了一个“手脚”,改变了这种默认行为。当请求创建 ProductController 实例时,我们给它创建了CustomerController
的实例。结果如下:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

其实更多的时候,我们自定义 controller 的激活机制是为了引入IoC,和 [ASP.NET
MVC 小牛之路]05 - 使用 Ninject 讲的通过继承 DefaultControllerFactory 引入 IoC 是一个道理。


自定义 Action Invoker

当 Controller Factory 创建好了一个类的实例后,MVC框架则需要一种方式来调用这个实例的 action 方法。如果创建的 controller 是继承 Controller 抽象类的,那么则是由 Action Invoker 来完成调用 action 方法的任务,MVC 默认使用的是 ControllerActionInvoker 类。如果是直接继承 IController 接口的 controller,那么就需要手动来调用 action 方法,见上一篇 [ASP.NET
MVC 小牛之路]09 - Controller 和 Action (1) 。下面我们通过自定义一个 Action Invoker 来了解一下 Action Invoker 的运行机制。

创建一个自定义的 Action Invoker 需要实现 IActionInvoker 接口,该接口的定义如下:

public interface IActionInvoker { 
    bool InvokeAction(ControllerContext controllerContext, string actionName); 
}
로그인 후 복사

这个接口只有一个 InvokeAction 方法。ControllerContext 对象参数包含了调用该方法的controller的信息,string类型的参数是要调用的Action方法的名称,这个名称来源于路由系统。返回值为bool类型,当actoin方法被找到并被调用时返回true,否则返回false。

下面是实现了IActionInvoker接口的 CustomActionInvoker 类:

using System.Web.Mvc;

namespace MvcApplication2.Infrastructure {
    public class CustomActionInvoker : IActionInvoker {
        public bool InvokeAction(ControllerContext controllerContext, string actionName) {
            if (actionName == "Index") {
                controllerContext.HttpContext.Response.Write("This is output from the Index action");
                return true;
            }
            else {
                return false;
            }
        }
    }
}
로그인 후 복사

这个 CustomActionInvoker 不需要关心实际被调用的Action方法。如果请求的是Index Action,这个 Invoker 通过 Response 直接输出一个消息,如果不是请Index Action,则会引发一个404-未找到错误。

决定Controller使用哪个Action Invoker是由 Controller 中的 Controller.ActionInvoker 属性来决定的,由它来告诉MVC当前的 controller 将使用哪个 Action Invoker 来调用 Action 方法。如下我们创建一个ActionInvokerController,并在它的构造函数中指定了 Action Invoker 为我们自定义的 Action Invoker:

namespace MvcApplication2.Controllers {
    public class ActionInvokerController : Controller {
        public ActionInvokerController() {
            this.ActionInvoker = new CustomActionInvoker();
        }
    }
}
로그인 후 복사

这个 controller 中没有 Action 方法,它依靠 CustomActionInvoker 来处理请求。运行程序,将URL定位到 /ActionInvoker/Index 可见如下结果:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

如果将URL定位到 ActionInvoker 下的其他Action,则会返回一个404的错误页面。

我们不推荐去实现自己的Action Invoker。首先内置的Action Invoker提供了一些非常有用的特性;其次是缺乏可扩展性和对View的支持等。这里只是为了演示和理解MVC框架处理请求过程的细节。


使用内置的 Action Invoker

通过自定义 Action Invoker,我们知道了MVC调用 Action 方法的机制。我们创建一个继承自 Controller 抽象类的 controller,如果不指定Controller.ActionInvoker,那么MVC会使用内置默认的Action Invoker,它是 ControllerActionInvoker 类。它的工作是把请求匹配到对应的 Action 方法并调用之,简单说就是寻找和调用 Action 方法。

为了让内置的 Action Invoker 能匹配到 Action 方法,Action方法必须满足下面的标准:

必须是公共的(public)。
不能是静态的(static)。
不能是System.Web.Mvc.Controller中存在的方法,或其他基类中的方法。如方法不能是 ToString 和 GetHashCode 等。
不能是一个特殊的名称。所谓特殊的名称是方法名称不能和构造函数、属性或者事件等的名称相同。

注意,Action方法也不能带有泛型,如MyMethod(),虽然 Action Invoker 能匹配到,但会抛出异常。

内置的 Action Invoker 给我们提供了很多实用的特性,给开发带来很大便利,下面两节内容可以说明这一点。


给 Action 方法定义别名

默认情况下,内置的Action Invoker (ControllerActionInvoker)寻找的是和请求的 action 名称相同的 action 方法。比如路由系统提供的 action 值是 Index,那么 ControllerActionInvoker 将寻找一个名为 Index 的方法,如果找到了,它就用这个方法来处理请求。ControllerActionInvoker 允许我们对此行为进行调整,即可以通过使用 ActionName 特性对 action 使用别名,如下对 CustomerController
的 List action 方法使用 ActionName 特性:

public class CustomerController : Controller {
    ...
    [ActionName("Enumerate")]
    public ViewResult List() {
        return View("Result", new Result {
            ControllerName = "Customer",
            ActionName = "List"
        });
    }
}
로그인 후 복사

当请求 Enumerate Action 时,将会使用 List 方法来处理请求。下面是请求 /Customer/Enumerate 的结果:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

这时候对 /Customer/List 的请求则会无效,报“找不到资源”的错误,如下:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

使用 Action 方法别名有两个好处:一是可以使用非法的C#方法名来作为请求的 action 名,如 [ActionName("User-Registration")]。二是,如果你有两个功能不同的方法,有相同的参数相同的名称,但针对不同的HTTP请求(一个使用 [HttpGet],另一个使用 [HttpPost]),你可以给这两个方法不同的方法名,然后使用 [ActionName] 来指定相同的 action 请求名称。


Action 方法选择器

我们经常会在 controller 中对多个 action 方法使用同一个方法名。在这种情况下,我们就需要告诉 MVC 怎样在相同的方法名中选择正确的 action 方法来处理请求。这个机制称为 Action 方法选择,它在基于识别方法名称的基础上,允许通过请求的类型来选择 action 方法。MVC 框架可使用C#特性来做到这一点,所以这种作用的特性可以称为 Action 方法选择器。

内置 Action 方法选择器

MVC提供了几种内置的特性来支持 Action 方法选择,它包括HttpGet、HttpPost、HttpPut 和 NonAction 等。这些选择器从名字上很容易理解什么意思,这里就不解释了。下面举个 NonAction 的例子。在 CustomerController 中添加一个 MyAction 方法,然后应用 [NonAction] 特性,如下:

public class CustomerController : Controller {
    ...
    [NonAction]
    public ActionResult MyAction() {
        return View();
    }
}
로그인 후 복사

使用 [NonAction] 后,方法将不会被识别为 action 方法,如下是请求 /Customer/MyAction 的结果:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

当然我们也可以通过把方法声明为 private 来告诉MVC它不是一个 action 方法。

自定义 Action 方法选择器

除了使用内置的Action方法选择器外,我们也可以自定义。所有的 action 选择器都继承自 ActionMethodSelectorAttribute 类,这个类的定义如下:

using System.Reflection; 

namespace System.Web.Mvc { 
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
    public abstract class ActionMethodSelectorAttribute : Attribute { 
        public abstract bool IsValidForRequest(ControllerContext controllerContext,  MethodInfo methodInfo); 
    } 
}
로그인 후 복사

它是一个抽象类,只有一个抽象方法:IsValidForRequest。通过重写这个方法,可以判断某个请求是否允许调用 Action 方法。

我们来考虑这样一种情况:同一个URL请求,在本地和远程请求的是不同的 action (如对于本地则绕过权限验证可能需要这么做)。那么自定义一个本地的 Action 选择器会是一个不错的选择。下面我们来实现这样一个功能的 Action 选择器:

using System.Reflection;
using System.Web.Mvc;

namespace MvcApplication2.Infrastructure {
    public class LocalAttribute : ActionMethodSelectorAttribute {
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
            return controllerContext.HttpContext.Request.IsLocal;
        }
    } 
}
로그인 후 복사

修改 CustomerController,添加一个LocalIndex 方法,并对它应用 “Index”别名,代码如下:

public class CustomerController : Controller {
        
    public ViewResult Index() {
        return View("Result", new Result {
            ControllerName = "Customer",
            ActionName = "Index"
        });
    }

    [ActionName("Index")]
    public ViewResult LocalIndex() {
        return View("Result", new Result {
            ControllerName = "Customer",
            ActionName = "LocalIndex"
        });
    }
    ...          
}
로그인 후 복사

这时如果请求 /Customer/Index,这两个 action 方法都会被匹配到而引发歧义问题,程序将会报错:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

这时候我们再对 LocalIndex 应用我们自定义的 Local 选择器:

...
[Local]
[ActionName("Index")]
public ViewResult LocalIndex() {
    return View("Result", new Result {
        ControllerName = "Customer",
        ActionName = "Index"
    });
}
...
로그인 후 복사

程序在本地运行的时候则会匹配到 LocalIndex action方法,结果如下:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

通过这个例子我们也发现,定义了选择器特性的Action方法被匹配的优先级要高于没有定义选择器特性的Action方法。


异步 Controller

对于 ASP.NET 的工作平台 IIS,它维护了一个.NET线程池用来处理客户端请求。这个线程池称为工作线程池(worker thread pool),其中的线程称为工作线程(worker threads)。当接收到一个客户端请求,一个工作线程从工作线程池中被唤醒并处理接收到的请求。当请求被处理完了后,工作线程又被这个线程池回收。这种线程程池的机制对ASP.NET应用程序有如下两个好处:

通过线程的重复利用,避免了每次接收到一个新的请求就创建一个新的线程。
线程池维护的线程数是固定的,这样线程不会被无限制地创建,减少了服务器崩溃的风险。

一个请求是对应一个工作线程,如果MVC中的action对请求处理的时间很短暂,那么工作线程很快就会被线程池收回以备重用。但如果执行action的工作线程需要调用其他服务(如调用远程的服务,数据的导入导出),这个服务可能需要花很长时间来完成任务,那么这个工作线程将会一直等待下去,直到调用的服务返回才继续工作。这个工作线程在等待的过程中什么也没做,资源浪费了。设想一下,如果这样的action一多,所有的工作线程都处于等待状态,大家都没事做,而新的请求来了又没人理,这样就陷入了尴尬境地。

解决这个问题需要使用异步(asynchronous) Controller,异步Controller允许工作线程在等待(await)的时候去处理别的请求,这样做减少了资源浪费,有效提高了服务器的性能。

使用异步 Controller 需要用到.NET 4.5的新特性:异步方法。异步方法有两个新的关键字:await 和 async。这个新知识点朋友们自己去网上找找资料看吧,这里就不讲了,我们把重点放在MVC中的异步 Controller 上。

在Models文件夹中添加一个 RemoteService 类,代码如下:

using System.Threading;
using System.Threading.Tasks;

namespace MvcApplication2.Models {

    public class RemoteService {

        public async Task<string> GetRemoteDataAsync() {
            return await Task<string>.Factory.StartNew(() => {
                Thread.Sleep(2000);
                return "Hello from the other side of the world";
            });
        }
    }
}
로그인 후 복사

然后创建一个名为 RemoteData 的 Controller,让它继承自 AsyncController 类,代码如下:

using System.Web.Mvc;
using MvcApplication2.Models;
using System.Threading.Tasks;

namespace MvcApplication2.Controllers {
    public class RemoteDataController : AsyncController {
        public async Task<ActionResult> Data() {
            
            string data = await new RemoteService().GetRemoteDataAsync();
            Response.Write(data);
            
            return View("Result", new Result {
                ControllerName = "RemoteData",
                ActionName = "Data"
            });
        }
    }
}
로그인 후 복사

运行程序,URL 定位到 /RemoteData/Data,2秒后将显示如下结果:

[ASP.NET MVC Mavericks Road] 10 - 컨트롤러와 액션(2)

当请求 /RemoteData/Data 时,Data 方法开始执行。当执行到下面代码调用远程服务时:

string data = await new RemoteService().GetRemoteDataAsync();
로그인 후 복사

工作线程开始处于等待状态,在等待过程中它可能被派去处理新的客户端请求。当远程服务返回结果了,工作线程再回来处理后面的代码。这种异步机制避免了工作线程处于闲等状态,尽可能的利用已被激活的线程资源,对提高MVC应用程序性能是很有帮助的。、


评论精选

提问 by 卤鸽:

IActionInvoker是在Controller.Excute方法中被调用,主要是查询具体的Action 处理方法,其实整个请求的过程都是从MvcHandler进行开始的。这是我的理解。不知正确否?

回答 by Liam Wang

是这么个意思,但不太严谨。确切一点说,Excute 方法是(自定义或默认的)ActionInvoker 的入口函数。 ActionInvoker 必须实现 IActionInvoker 接口来查找和调用 Action 方法。本文没有介绍 MvcHandler 的知识。MvcHandler 是处理Controller的开始,但在MvcHandler 之前还有一个MvcRouteHandler,当请求经过路由解析后,MvcRouteHandler 实例会生成一个 MvcHandler 实例,并把请求交给它。MvcHandler
会从Controller 工厂中获取一个 Controller 实例,然后由 Controller 来具体地处理请求。

 以上就是[ASP.NET MVC 小牛之路]10 - Controller 和 Action (2)的内容,更多相关内容请关注PHP中文网(www.php.cn)!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!