ASP.NET MVC Extensibility

  • 4,624 views
Uploaded on

One of the best features of ASP.NET MVC is that it's totally extensible: if you don't like the way the framework works or if you have scenarios not covered by it, you can change the behaviors by …

One of the best features of ASP.NET MVC is that it's totally extensible: if you don't like the way the framework works or if you have scenarios not covered by it, you can change the behaviors by extending the defaults or by writing your owns.
In this presentation I'll go through all the main extensibility points and explain how to leverage the main ones

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
4,624
On Slideshare
0
From Embeds
0
Number of Embeds
6

Actions

Shares
Downloads
127
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Explainhow route selectionworks
  • 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

Transcript

  • 1. Extending ASP.NET MVC
    Part 1
    Simone ChiarettaArchitect, Council of the EU
    http://codeclimber.net.nz
    Twitter: @simonech
    June 23rd, 2010
  • 2. Who the hell am I?
    Simone Chiaretta
    Microsoft MVP ASP.NET
    ASP Insider
    Blogger – http://codeclimber.net.nz
    ItalianALT.NET UG Founder
    OpenSource developer
    Climber
    All Around Nice Guy
    Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"
  • 3. Agenda
    The default ASP.NET MVC Pipeline
    Extensibilitypoints’ list
    The Mostimportantextensibilitypoints
  • 4. The DefaultASP.NET MVC Pipeline
  • 5. The default ASP.NET MVC Pipeline
    4
  • 6. The default components
    URL Routing:
    Parses the URL, andinstantiate the MvcHandler
    Controller Factory
    Takes URL parameters, create controller via reflectionbased on Controllername
    Action Invoker
    Invokes the actionbased on thename, with the filtersbefore and after
    ViewEngine
    WebFormsviewengine
    Template
    Renders a TextBoxalmostforeverything
    HtmlHelper
    Has a bunch of standardmethods
  • 7. ASP.NET MVC IS extensible
    Ifyou don’t likethem
    Ifyouneedsomething else
    Changethem
  • 8. ASP.NET MVC IS extensible
    Almosteveryaspectof the framework can beextented/replaced
  • 9. Extensibilitypoints’ list
  • 10. Routingextensibility
    RouteConstraint
    Validatesrouteparameterswith code
    RouteHandler
    Defineshow the requestmustbehandled
  • 11. Controller Extensibility
    ControllerFactory
    ResponsibleforcreatingControllers
    ActionInvoker
    Invokesanaction, basedonly on itsname
    ActionMethodSelectorAttribute
    Helps the actioninvoker decide whichactiontoinvokewhen the nameisnotunique
    Controller
    The base classforevery controller
    ActionResult
    Decideshowtosend the output to the user
  • 12. ActionFilterExtensibility
    AuthorizationFilter
    Makessure the currentrequestisallowed
    ActionFilters
    Executedbefore or after the actionexecutes
    ResultFilters
    Executedbefore or afteranactionresultexecutes
  • 13. Binding/ValidationExtensibility
    ModelBinder
    Populates the actionmethodparametersfrom the request
    ModelValidator Provider
    Retrieves the validationrules
    Server-sideValidationRules
    The actual server-side validationrule
  • 14. ViewExtensibility
    ViewEngine
    The service thattransforms in HTML the data for the user
    HtmlHelpers
    Utility functionsthathideaway the generation of some HTML markup or JavaScript code
    Client-sideValidationRules
    Client-sidevalidationrules
    ModelMetadata Provider
    Retrieves the metadataneededfor the templatedhelpers
    Custom Templates
    Renders the html toedit/display specifictypes
  • 15. The Mostimportantextensibilitypoints
  • 16. The MostimportantExtensibilitpoints
    The onesyouwilldefinitelyuse
    The onesyouhaveto start using
    The onesyoumight or mightnotneedtouse
    The onesyoumostlikelywillnotwriteyourself
    butprobablyusewrittenbyothers
  • 17. Extensibilitypointsyouwilluse
  • 18. CustomTemplates
  • 19. CustomTemplates
    • WHAT: Renders the html toedit/display specifictypes
    DEFAULT: Everythingis a label or a textbox
    WHY: Addyourowntocustomizespecificdata-types
  • 20. CustomTemplates
    AddPartialViews in:
    /Views/Shared/DisplayTemplates
    /Views/Shared/EditorTemplates
    Demo
  • 21. Server-sideValidationRules
  • 22. Server-sideValidationRules
    WHAT: Definehow a propertyisvalidated in the server side validation
    DEFAULT: Required, Length, wrong type
    WHY: Addyourownrules
  • 23. Server-sideValidationRules
    Write a newValidationAttribute
    Implement the IsValidmethod
    Applyattributetoyourmodel
    Demo
  • 24. Client-sideValidationRules
  • 25. Client-sideValidationRules
    WHAT: Definehow a propertyisvalidated in the client-side validation
    DEFAULT: Client-sidecounterparts of the default server-side validators
    WHY: Addyourownvalidators
  • 26. Client-sideValidationRules
    First make a server-side validator
    Makevalidationlogic in JavaScript
    Writeadaptertopushvalidationrulesto client-side
    Registervalidationfunction via JS
    Registeradapter in Global.asax
    Demo
  • 27. Extensibilitypointsyouhaveto start using
  • 28. Base Controller
  • 29. Base Controller
    WHAT: The base class forevery Controller
    DEFAULT: Defaultimplementation of helpermethods
    WHY: Extendifyouwanttoenforceyouownconventions
  • 30. Base Controller
    Override Controller
    YourcontrollersoverridefromBaseControllerinsteadof Controller
    Demo
  • 31. HtmlHelpers
  • 32. HtmlHelpers
    WHAT: Utility functionsthathideaway the generation of HTML markup or JavaScript code
    DEFAULT: Html.TextBox, Html.Encode, Html.Partial, …
    WHY: “Ifthereisanif, writeanHelper”
  • 33. HtmlHelpers
    Add new methodsasextensionmethods
    Demo
  • 34. Rating
    If you liked this talk, please consider rating it:
    http://speakerrate.com/talks/3669-asp-net-mvc-extensibility
    33
    Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"
  • 35. Extending ASP.NET MVC
    Part 2
    Simone ChiarettaArchitect, Council of the EU
    http://codeclimber.net.nz
    Twitter: @simonech
    June 23rd, 2010
  • 36. Filters
  • 37. AuthorizationFilter
    WHAT: Makes sure the current request is allowed
    DEFAULT: Itisbased on the ASP.NETMembership provider
    WHY: ChangeifyouwantnottouseASP.NET MVC or ifyouwanttoenhance the routedictionary
  • 38. Action Filters
    WHAT: Executed before or after the action executes
    DEFAULT: Output cache
    WHY: Addyourownbased on yourneeds
  • 39. ResultFilters
    WHAT: Executed before or after an action result executes
    DEFAULT: No default resultfilters
    WHY: Addyourownbased on yourneeds
  • 40. AuthorizationFilter
    ImplementIAuthorizationFilter
    OnAuthorization
  • 41. Filters
    ImplementIActionFilter + IResultFilter
    MakenewActionFilterAttribute
    OnActionExecuting
    OnActionExecuted
    ImplementIResultFilter
    OnResultExecuting
    OnResultExecuted
  • 42. Extensibilitypointsyoumightwanttouse
  • 43. RouteConstraint
  • 44. RouteConstraint
    WHAT: Validates route parameters
    DEFAULT: No default implementation
    WHY: Addyourownwhenneeded
  • 45. RouteConstraint
    Implement
    IRouteConstraint.Match
    Inspectrequest and returntrue or false
    Demo
  • 46. RouteHandler
  • 47. RouteHandler
    WHAT: Defineshow the requestmustbehandled
    DEFAULT: Routes the requesttoMvcHandler
    WHY: ChangeifyouwantnottouseASP.NET MVC
  • 48. RouteHandler
    Implement
    IRouteHandler.GetHttpHandler
    Demo
  • 49. ActionMethodSelectorAttribute
  • 50. ActionMethodSelectorAttribute
    WHAT: Helps the action invoker decide which action to invoke when the name is not unique
    DEFAULT: HttpMethod attributes: decide based on the HttpMethod
    WHY: Addyourowntosupportdifferentscenarios
  • 51. ActionMethodSelectorAttribute
    Create newAttibuteinheritingfrom
    ActionMethodSelectorAttribute
    Implement:
    IsValidForRequest
    Demo
  • 52. ActionResult
  • 53. ActionResult
    WHAT: Sends the output to the user
    DEFAULT: ViewResult, RedirectResult, FileResult, JsonResult, etc…
    WHY: Addyourownifyouneedan output notavailable in the default results
  • 54. ActionResult
    Create a new resultinheritingfrom:
    ActionResult
    Implement:
    ExecuteResult
    Optionally create anhelpermethod in you “base controller”
    Demo
  • 55. ModelBinder
  • 56. ModelBinder
    WHAT: Populates the action method parameters from the request
    DEFAULT: Bindsrequest’s valuesbased on names
    WHY: Extendifyouneedtoaddother way ofbinding
  • 57. ModelBinder
    ImplementIModelBinder
    BindModel
    InheritfromDefaultModelBinder
    BindProperty
    OnModelUpdated
    OnModelUpdating
    Register the ModelBinder
    Demo
  • 58. Veryunlikelytowriteyourown
  • 59. ControllerFactory
  • 60. Controller Factory
    WHAT: Responsible for creating Controllers
    DEFAULT: Create aninstance of the Controller via Reflectionbased on itsname
    WHY: Changeifyouwantto create the controller in otherways or ifyouwanttoadd some funtionalities
    Most of themainIoC container have a customControllerFactory
  • 61. Controller Factory
    ImplementIControllerFactory
    CreateController
    ReleaseController
    OverrideDefaultControllerFactory
    GetControllerInstance(TypecontrollerType)
    Demo
  • 62. ActionInvoker
  • 63. ActionInvoker
    WHAT: Invokes an action, based only on its name
    DEFAULT: Call the actionmethod, via reflection, based on itsname, gatheringfilters via attributes and callingthembefore and after
    WHY: Changeifyouwanttochange the way methods are called, or wantdifferent way toconfigureFilters
  • 64. ActionInvoker
    Implement IActionInvoker
    InvokeAction
    OverrideControllerActionInvoker
    InvokeActionMethodWithFilters
    InvokeActionResultWithFilters
    GetFilters

    Demo
  • 65. ViewEngine
  • 66. ViewEngine
    WHAT: The service that transforms in HTML the data for the user
    DEFAULT: WebFormviewengine
    WHY: Changeifyou don’t like the WebFormapproach
  • 67. ViewEngine
    IViewEngine:
    UsuallyoverrideVirtualPathProviderViewEngine
    CreateView
    IView:
    Render
    Demo
  • 68. ModelValidatorProvider
  • 69. ModelValidatorProvider
    WHAT: Retrieves the validation rules
    DEFAULT: Validationrules are definedwithDataAnnotationattributes
    WHY: Changeifyouwanttospecifyvalidationrules in otherways (XML, Database, etc…)
  • 70. ModelValidatorProvider
    OverridefromModelValidatorProvider
    ImplementGetValidators
  • 71. ModelMetadataProvider
  • 72. ModelMetadataProvider
    WHAT: Retrieves the metadataneededfor the templatedhelpers
    DEFAULT: Metadata are definedwithDataAnnotationattributes
    WHY: Changeifyouwanttospecifymetadata in otherways (XML, Database, etc…)
  • 73. ModelMetadataProvider
    InheritfromModelMetadataProvider
    Implement
    GetMetadataForType
    GetMetadataForProperty
    GetMetadataForProperties
  • 74. Contacts – Simone Chiaretta
    MSN: simone_ch@hotmail.com
    Blog:
    English: http://codeclimber.net.nz/
    Italian: http://blogs.ugidotnet.org/piyo/
    Twitter: @simonech
    73
  • 75. Rating
    If you liked this talk, please consider rating it:
    http://speakerrate.com/talks/3669-asp-net-mvc-extensibility
    74
    Disclaimer:"The viewsexpressed are purelythose of the speaker and may not in anycircumstancesberegarded as stating an official position of the Council"