Extending ASP.NET MVCPart 1Simone ChiarettaArchitect, Council of the EUhttp://codeclimber.net.nzTwitter: @simonechJune 23rd, 2010
Who the hell am I?Simone ChiarettaMicrosoft MVP ASP.NETASP InsiderBlogger – http://codeclimber.net.nzItalianALT.NET UG FounderOpenSource developerClimberAll Around Nice GuyDisclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"
AgendaThe default ASP.NET MVC PipelineExtensibilitypoints’ listThe Mostimportantextensibilitypoints
The DefaultASP.NET MVC Pipeline
The default ASP.NET MVC Pipeline4
The default componentsURL Routing:Parses the URL, andinstantiate the MvcHandlerController FactoryTakes URL parameters, create controller via reflectionbased on ControllernameAction InvokerInvokes the actionbased on thename, with the filtersbefore and afterViewEngineWebFormsviewengineTemplateRenders a TextBoxalmostforeverythingHtmlHelperHas a bunch of standardmethods
ASP.NET MVC IS extensibleIfyou don’t likethemIfyouneedsomething elseChangethem
ASP.NET MVC IS extensibleAlmosteveryaspectof the framework can beextented/replaced
Extensibilitypoints’ list
RoutingextensibilityRouteConstraintValidatesrouteparameterswith codeRouteHandlerDefineshow the requestmustbehandled
Controller ExtensibilityControllerFactoryResponsibleforcreatingControllersActionInvokerInvokesanaction, basedonly on itsnameActionMethodSelectorAttributeHelps the actioninvoker decide whichactiontoinvokewhen the nameisnotuniqueControllerThe base classforevery controllerActionResultDecideshowtosend the output to the user
ActionFilterExtensibilityAuthorizationFilterMakessure the currentrequestisallowedActionFiltersExecutedbefore or after the actionexecutesResultFiltersExecutedbefore or afteranactionresultexecutes
Binding/ValidationExtensibilityModelBinderPopulates the actionmethodparametersfrom the requestModelValidator ProviderRetrieves the validationrulesServer-sideValidationRulesThe actual server-side validationrule
ViewExtensibilityViewEngineThe service thattransforms in HTML the data for the userHtmlHelpersUtility functionsthathideaway the generation of some HTML markup or JavaScript codeClient-sideValidationRulesClient-sidevalidationrulesModelMetadata ProviderRetrieves the metadataneededfor the templatedhelpersCustom TemplatesRenders the html toedit/display specifictypes
The Mostimportantextensibilitypoints
The MostimportantExtensibilitpointsThe onesyouwilldefinitelyuseThe onesyouhaveto start usingThe onesyoumight or mightnotneedtouseThe onesyoumostlikelywillnotwriteyourselfbutprobablyusewrittenbyothers
Extensibilitypointsyouwilluse
CustomTemplates
CustomTemplatesWHAT: Renders the html toedit/display specifictypesDEFAULT: Everythingis a label or a textboxWHY: Addyourowntocustomizespecificdata-types
CustomTemplatesAddPartialViews in:/Views/Shared/DisplayTemplates/Views/Shared/EditorTemplatesDemo
Server-sideValidationRules
Server-sideValidationRulesWHAT: Definehow a propertyisvalidated in the server side validationDEFAULT: Required, Length, wrong typeWHY: Addyourownrules
Server-sideValidationRulesWrite a newValidationAttributeImplement the IsValidmethodApplyattributetoyourmodelDemo
Client-sideValidationRules
Client-sideValidationRulesWHAT: Definehow a propertyisvalidated in the client-side validationDEFAULT: Client-sidecounterparts of the default server-side validatorsWHY: Addyourownvalidators
Client-sideValidationRulesFirst make a server-side validatorMakevalidationlogic in JavaScriptWriteadaptertopushvalidationrulesto client-sideRegistervalidationfunction via JSRegisteradapter in Global.asaxDemo
Extensibilitypointsyouhaveto start using
Base Controller
Base ControllerWHAT: The base class forevery ControllerDEFAULT: Defaultimplementation of helpermethodsWHY: Extendifyouwanttoenforceyouownconventions
Base ControllerOverride ControllerYourcontrollersoverridefromBaseControllerinsteadof ControllerDemo
HtmlHelpers
HtmlHelpersWHAT: Utility functionsthathideaway the generation of HTML markup or JavaScript codeDEFAULT: Html.TextBox, Html.Encode, Html.Partial, …WHY: “Ifthereisanif, writeanHelper”
HtmlHelpersAdd new methodsasextensionmethodsDemo
RatingIf you liked this talk, please consider rating it:http://speakerrate.com/talks/3669-asp-net-mvc-extensibility33Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"
Extending ASP.NET MVCPart 2Simone ChiarettaArchitect, Council of the EUhttp://codeclimber.net.nzTwitter: @simonechJune 23rd, 2010
Filters
AuthorizationFilterWHAT: Makes sure the current request is allowedDEFAULT: Itisbased on the ASP.NETMembership providerWHY: ChangeifyouwantnottouseASP.NET MVC or ifyouwanttoenhance the routedictionary
Action FiltersWHAT: Executed before or after the action executesDEFAULT: Output cacheWHY: Addyourownbased on yourneeds
ResultFiltersWHAT: Executed before or after an action result executesDEFAULT: No default resultfiltersWHY: Addyourownbased on yourneeds
AuthorizationFilterImplementIAuthorizationFilterOnAuthorization
FiltersImplementIActionFilter + IResultFilterMakenewActionFilterAttributeOnActionExecutingOnActionExecutedImplementIResultFilterOnResultExecutingOnResultExecuted
Extensibilitypointsyoumightwanttouse
RouteConstraint
RouteConstraintWHAT: Validates route parametersDEFAULT: No default implementationWHY: Addyourownwhenneeded
RouteConstraintImplementIRouteConstraint.MatchInspectrequest and returntrue or falseDemo
RouteHandler
RouteHandlerWHAT: Defineshow the requestmustbehandledDEFAULT: Routes the requesttoMvcHandlerWHY: ChangeifyouwantnottouseASP.NET MVC
RouteHandlerImplementIRouteHandler.GetHttpHandlerDemo
ActionMethodSelectorAttribute
ActionMethodSelectorAttributeWHAT: Helps the action invoker decide which action to invoke when the name is not uniqueDEFAULT: HttpMethod attributes: decide based on the HttpMethodWHY: Addyourowntosupportdifferentscenarios
ActionMethodSelectorAttributeCreate newAttibuteinheritingfromActionMethodSelectorAttributeImplement:IsValidForRequestDemo
ActionResult
ActionResultWHAT: Sends the output to the userDEFAULT: ViewResult, RedirectResult, FileResult, JsonResult, etc…WHY: Addyourownifyouneedan output notavailable in the default results
ActionResultCreate a new resultinheritingfrom:ActionResultImplement:ExecuteResultOptionally create anhelpermethod in you “base controller”Demo
ModelBinder
ModelBinderWHAT: Populates the action method parameters from the requestDEFAULT: Bindsrequest’s valuesbased on namesWHY: Extendifyouneedtoaddother way ofbinding
ModelBinderImplementIModelBinderBindModelInheritfromDefaultModelBinderBindPropertyOnModelUpdatedOnModelUpdatingRegister the ModelBinderDemo
Veryunlikelytowriteyourown
ControllerFactory
Controller FactoryWHAT: Responsible for creating ControllersDEFAULT: Create aninstance of the Controller via Reflectionbased on itsnameWHY: Changeifyouwantto create the controller in otherways or ifyouwanttoadd some funtionalitiesMost of themainIoC container have a customControllerFactory
Controller FactoryImplementIControllerFactoryCreateControllerReleaseControllerOverrideDefaultControllerFactoryGetControllerInstance(TypecontrollerType)Demo
ActionInvoker
ActionInvokerWHAT: Invokes an action, based only on its nameDEFAULT: Call the actionmethod, via reflection, based on itsname, gatheringfilters via attributes and callingthembefore and afterWHY: Changeifyouwanttochange the way methods are called, or wantdifferent way toconfigureFilters
ActionInvokerImplement IActionInvokerInvokeActionOverrideControllerActionInvokerInvokeActionMethodWithFiltersInvokeActionResultWithFiltersGetFilters…Demo
ViewEngine
ViewEngineWHAT: The service that transforms in HTML the data for the userDEFAULT: WebFormviewengineWHY: Changeifyou don’t like the WebFormapproach
ViewEngineIViewEngine:UsuallyoverrideVirtualPathProviderViewEngineCreateViewIView:RenderDemo
ModelValidatorProvider
ModelValidatorProviderWHAT: Retrieves the validation rulesDEFAULT: Validationrules are definedwithDataAnnotationattributesWHY: Changeifyouwanttospecifyvalidationrules in otherways (XML, Database, etc…)
ModelValidatorProviderOverridefromModelValidatorProviderImplementGetValidators
ModelMetadataProvider
ModelMetadataProviderWHAT: Retrieves the metadataneededfor the templatedhelpersDEFAULT: Metadata are definedwithDataAnnotationattributesWHY: Changeifyouwanttospecifymetadata in otherways (XML, Database, etc…)
ModelMetadataProviderInheritfromModelMetadataProviderImplementGetMetadataForTypeGetMetadataForPropertyGetMetadataForProperties
Contacts – Simone ChiarettaMSN: simone_ch@hotmail.comBlog:English: http://codeclimber.net.nz/Italian: http://blogs.ugidotnet.org/piyo/Twitter: @simonech73
RatingIf you liked this talk, please consider rating it:http://speakerrate.com/talks/3669-asp-net-mvc-extensibility74Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"

ASP.NET MVC Extensibility

Editor's Notes

  • #45 Explainhow route selectionworks
  • #61 Ifyou are dealingwith CLR types,gowithoverridingDefaultControllerFactory: youdon’t havetoresolve the controllertypebased on thename and youonlyneedto create theinstance of the controller givenitstype. Alldiscovery and filteringisdoneby the defaultimplementationIfyouwanttochange the namingconventions, or are notdealingwith CLR typesyouhaveto go the hard route and implementIController