AsyncState parameter of ASP. NET
This is because the default Model Binder cannot know how to obtain an AsyncCallback object from a context. This is quite simple. We only need to construct an AsyncCallbackModelBinder, and its BindModel method only extracts the AsyncCallback object saved in AsyncMvcHandler. BeginProcessRequest and returns it:
- public sealed class AsyncCallbackModelBinder : IModelBinder
- {
- public object BindModel(
- ControllerContext controllerContext,
- ModelBindingContext bindingContext)
- {
- return controllerContext.Controller.GetAsyncCallback();
- }
- }
When an application is started, it is registered as the default Binder of the AsyncCallback type:
- protected void Application_Start()
- {
- RegisterRoutes(RouteTable.Routes);
- ModelBinders.Binders[typeof(AsyncCallback)] = new AsyncCallbackModelBinder();
- }
You can use a similar method for the AsyncState parameter. However, this seems inappropriate because the object type is too broad and cannot explicitly represent the AsyncState parameter. In fact, even if you do not set a binder for asyncState, The AsyncState is always null for an asynchronous ASP. NET Request. If you must specify a binder, we recommend that you mark the following Attribute on the asyncState parameter of each Action method. It and AsyncStateModelBinder are also created in the project:
- [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
- public sealed class AsyncStateAttribute : CustomModelBinderAttribute
- {
- private static AsyncStateModelBinder s_modelBinder = new AsyncStateModelBinder();
-
- public override IModelBinder GetBinder()
- {
- return s_modelBinder;
- }
- }
The usage is as follows:
- [AsyncAction]
- public ActionResult AsyncAction(AsyncCallback cb, [AsyncState]object state) { ... }
In fact, the Controller-based extension methods GetAsyncCallback and GetAsyncState are both public methods, you can also make the Action method not accept the two parameters and get them directly from the Controller-of course, this method reduces testability and is not worth advocating. The above describes the AsyncState parameters of ASP. NET.
- Introduction to ASP. NET 2.0 Virtual Hosts
- Introduction to ASP. NET Applications
- Optimize ASP. NET 2.0 Profile Provider
- ASP. NET pipeline Optimization
- Introduction to ASP. NET Routing Engine