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