45
MVC Internals & Extensibility Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com

Asp.Net Mvc Internals & Extensibility

Embed Size (px)

DESCRIPTION

Asp.Net Mvc Internals & Extensibility

Citation preview

Page 1: Asp.Net Mvc Internals & Extensibility

MVC Internals & Extensibility

Eyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com

Page 2: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Agenda

Routing

Dependency Resolver

Controller Extensibility

Model Extensibility

View Extensibility

Page 3: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

MVC in ASP.NET

Page 4: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

MVC Execution ProcessASP.NET

IIS Routing ASP.NET MVC 3.0

Page 5: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

URL Routing

http://Domain/Path

http://Domain/.../..

URL to Controller

URL to Page

Page 6: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Routes A route is a URL pattern that is mapped to a

handler. The handler can be a physical file, such as an .aspx file in a

Web Forms application. A handler can also be a class that processes the request,

such as a controller in an MVC application.

protected void Application_Start(){    RouteTable      .Routes      .MapRoute(         "Default",   // Route name         "{controller}/{action}/{id}", // URL template         new { controller="Calc", action="Add", id=UrlParameter.Optional }       );}

Global.asax

Page 7: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Route lifecycle

Page 8: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Route

IDependencyResolver

MvcRouteHandler MvcHandler Controller

Routing Process

Page 9: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

URL PatternsRoute definition Example of matching URL

{controller{/}action{/}id } /Products/show/beverages {table/}.Details aspx /Products/Details.aspx

blog/{action}/{entry} /blog/show/123 {reporttype{/}year{/}month{/}day } /sales/2008/1/5

{locale{/}action } /US/show {language{-}country{/}action } /en-US/show

Page 10: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

URL Patterns in MVC Applications

{Controller} / {Action} / {id}

Query / {queryname} / {*queryvalues} “*” This is referred to as a catch-all parameter.

/query/select/bikes/onsale queryname = "select" , queryvalues = "bikes/onsale"

Page 11: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Adding Constraints to Routes Constraints are defined by using regular

expressions string or by using objects that implement the IRouteConstraint interface.

protected void Application_Start(){    RouteTable      .Routes      .MapRoute(         "Blog",         "Posts/{postDate}",          new { controller="Blog",action="GetPosts" }       );}

/Posts/28-12-71 => BlogController,GetPosts( “28-12-1971” )/Post/28 => BlogController,GetPosts( “28” )/Post/test => BlogController,GetPosts( “test” )

Global.asax

Page 12: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

IRouteConstraintprotected void Application_Start(){    RouteTable      .Routes      .MapRoute(         "Default",   // Route name                            "{controller}/{action}/{id}", // URL template         new { controller="Calc", action="Add", id=UrlParameter.Optional }, new { action = new MyRouteConstraint() }       );} Custom Route Constraint

Global.asax

Page 13: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Regular Expression Route Constraint

protected void Application_Start(){    RouteTable      .Routes      .MapRoute(         "Default",   // Route name                            "{controller}/{action}/{id}", // URL template         new { controller="Calc", action="Add", id=UrlParameter.Optional }, new { action = @"\d{2}-\d{2}-\d{4}"  }       );} Regular Expression

Page 14: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Custom Route Constraint

Page 15: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Dependency Resolver Service locator for the framework.

protected void Application_Start()         {    AreaRegistration.RegisterAllAreas();    RegisterGlobalFilters(GlobalFilters.Filters);    RegisterRoutes(RouteTable.Routes);

    DependencyResolver         .SetResolver(new TraceDependencyResolver() );         }

Page 16: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Factories and Providers

Page 17: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Dependency Resolver

Page 18: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Controller Extensibility

Page 19: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Controller & Filters The Controller class implements each of the

filter interfaces. You can implement any of the filters for a

specific controller by overriding the controller's On<Filter> method. OnAuthorization OnActionExecuting OnActionExecuted OnResultExecuting OnResultExecuted OnException

Page 20: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Action Method Action Result

Page 21: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

ASP.NET MVC Filters Filters are custom classes that provide both a

declarative and programmatic means to add pre-action and post-action behavior to controller action methods.

[HandleError] [Authorize]public class CourseController : Controller{ [HandleError] [OutputCache] [RequireHttps]   public ActionResult Net( string name )   {       ViewBag.Course = BL.GetCourse(name);       return View();   }}

Page 22: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

IAuthorizationFilter Make security decisions about whether to

execute an action method. AuthorizeAttribute

RequireHttpsAttribute

Page 23: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

IActionFilter Interface OnActionExecuting

Runs before the action method.

OnActionExecuted Runs after the action method

Page 24: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

IResultFilter Interface OnResultExecuting

Runs before the ActionResult object is executed.

OnResultExecuted Runs after the result. Can perform additional processing of the result. The OutputCacheAttribute is one example of a result filter.

Page 25: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

IExceptionFilter Execute if there is an unhandled exception

thrown during the execution of the ASP.NET MVC pipeline. Can be used for logging or displaying an error page.

HandleErrorAttribute is one example of an exception filter.

Page 26: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Filter Order Filters run in the following order:

Authorization filters

Action filters

Response filters

Exception filters

Page 27: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Controller Context1

2 3 4 5

6

Page 28: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Filters

Page 29: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Custom Filter You can create a filter in the following ways:

Override one or more of the controller's On<Filter> methods.

Create an attribute class that derives from ActionFilterAttribute or FilterAttribute.

Register a filter with the filter provider (the FilterProviders class).

Register a global filter using the GlobalFilterCollection class.

Page 30: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Custom Filter

Page 31: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Filter Providers By default, ASP.NET MVC registers the

following filter providers: Filters for global filters.

FilterAttributeFilterProvider for filter attributes.

ControllerInstanceFilterProvider for controller instances.

The GetFilters method returns all of the IFilterProvider instances in the service locator.

Page 32: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

The Filter Provider Interface

Page 33: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Extensibility

Page 34: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Binders Binders are like type converters, because they

can convert HTTP requests into objects that are passed to an action method.

Page 35: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Page 36: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Model Binder Types

ByteArrayModelBinder

LinqBinaryModelBinder

FormCollectionModelBinder

HttpPostedFileBaseModelBinder

DefaultModelBinder

Page 37: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

DefaultModelBinder Class Translate HTTP request

information into complex models, including nested types and arrays.  It does this through a naming

convention, which is supported at both the HTML generation (HTML helpers) and the consumption side (model binders).

Page 38: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Custom Model Binders ASP.NET MVC allows us to override both the

default model binder, as well as add custom model binders.

ModelBinders.Binders.DefaultBinder = new CustomDefaultBinder();

ModelBinders.Binders.Add( typeof(DateTime), 

new DateTimeModelBinder() );

Page 39: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

ModelBinder Attribute Represents an attribute that is used to

associate a model type to a model-builder type.

public ActionResult Contact( [ModelBinder(typeof(ContactBinder))] Contact contact ){      ViewData["name"]  = contact.Name;      ViewData["email"]  = contact.Email;      ViewData["message"] = contact.Message;      ViewData["title"]  = "Succes!";

      return View();}

Page 40: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Custom Binder

Page 41: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

public ActionResult Contact( [ModelBinder(typeof(ContactBinder))] Contact contact ){      ViewData["name"]  = contact.Name;      ViewData["email"]  = contact.Email;      ViewData["message"] = contact.Message;      ViewData["title"]  = "Succes!";

      return View();}

Page 42: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

View Extensibility

Page 43: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Page 44: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Page 45: Asp.Net Mvc Internals & Extensibility

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]