ASP.NET的AsyncState參數
ASP.NET的AsyncState參數
這是因為默認的Model Binder無法得知如何從一個上下文環境中得到一個AsyncCallback對象。這一點倒非常簡單,我們只需要構造一個AsyncCallbackModelBinder,而它的BindModel方法僅僅是將AsyncMvcHandler.BeginProcessRequest方法中保存的AsyncCallback對象取出并返回:
- public sealed class AsyncCallbackModelBinder : IModelBinder
- {
- public object BindModel(
- ControllerContext controllerContext,
- ModelBindingContext bindingContext)
- {
- return controllerContext.Controller.GetAsyncCallback();
- }
- }
其使用方式,便是在應用程序啟動時將其注冊為AsyncCallback類型的默認Binder:
- protected void Application_Start()
- {
- RegisterRoutes(RouteTable.Routes);
- ModelBinders.Binders[typeof(AsyncCallback)] = new AsyncCallbackModelBinder();
- }
對于AsyncState參數您也可以使用類似的做法,不過這似乎有些不妥,因為object類型實在過于寬泛,并不能明確代指AsyncState參數。事實上,即使您不為asyncState設置binder也沒有太大問題,因為對于一個異步ASP.NET請求來說,其AsyncState永遠是null。如果您一定要指定一個binder,我建議您在每個Action方法的asyncState參數上標記如下的Attribute,它和AsyncStateModelBinder也已經被一并建入項目中了:
- [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;
- }
- }
使用方式如下:
- [AsyncAction]
- public ActionResult AsyncAction(AsyncCallback cb, [AsyncState]object state) { ... }
其實,基于Controller的擴展方法GetAsyncCallback和GetAsyncState均為公有方法,您也可以讓Action方法不接受這兩個參數而直接從Controller中獲取——當然這種做法降低了可測試性,不值得提倡。以上介紹ASP.NET的AsyncState參數
【編輯推薦】