5. ASP.NET MVC
• A new presentation option for ASP.NET
• Simpler way to program ASP.NET
• Easily testable and TDD friendly
• More control over your <html/>
• More control over your URLs
• Supports existing ASP.NET features
• Removes: viewstate and postback needs
7. Routing - example
public class OrdersController : Controller
{
public ActionResult Index()
{
}
public ActionResult Details(int id)
{
}
}
http://www.yoursite.com/Orders/Details/1
13. Controller
public class OrdersController : Controller
{
public ActionResult Details(int? id)
{
Order order = db.Orders.Find(id);
if (order == null)
return HttpNotFound();
return View(order);
}
}
View("MyWonderfulOrderView", order);
14. Controller – routing and HTTP methods
public class OrdersController : Controller
{
// GET: Orders/Edit/5
public ActionResult Edit(int? id)
{
}
// POST: Orders/Edit/5
[HttpPost]
public ActionResult Edit(Order order)
{
}
}
18. View
• Related to controllers/actions by naming convetion
• Several View Engine. Standard: Razor, WebFormViewEngine
• Support layouts and partial views
• Can use strongly-typed model (e.g. Order) or dynamic one (ViewBag)
• @Html helper methods (e.g. @Html.TextBoxFor)
• @Html methods can be extended
19. ActionResult
• ActionResult is the base class for action’s return types
• Available results:
• ViewResult - Renders a specifed view to the response stream
• RedirectResult - Performs an HTTP redirection to a specifed URL
• RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by
the routing engine, based on given route data
• JsonResult - Serializes a given ViewData object to JSON format
• ContentResult - Writes content to the response stream without requiring a view
• FileContentResult - Returns a file to the client
• and more
20. Model binder
• Transform values from client to .NET class instances or primitive types
• Retrieves values from HTML form variables, POSTed variables, query string
and routing parameters
• DefaultModelBinder is the default binder
• Binding can be customized, for specific types at application level or at action’s
parameter level
21. Filters
• Enable Aspect Oriented Programming (AOP)
• Different types for different needs:
• Authorization filters – IAuthorizationFilter
• Action filters – IActionFilter
• Result filters – IResultFilter
• Exception filters – IExceptionFilter
• Filters can be applied to a single action or a whole controller
23. ASP.NET Web API
• Formerly part of WCF framework
• 2012 – First release
• 2013 – Release of Web API 2
• First class framework for HTTP-based services
• Foundamental for creating RESTful services
• Self-hosted
• Different stacks, same concepts – System.Web.Mvc System.Web.Http
24. ASP.NET Web API cf. MVC
• Similar route patterns declarations
• Request/method name matching by HTTP verbs
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
25. ASP.NET Web API cf. MVC
GET http://www.yoursite.com/api/Orders/5
public class OrdersController : ApiController
{
IQueryable<Order> GetOrders() { … }
IHttpActionResult GetOrder(int id) { … }
IHttpActionResult PutOrder(int id, Order order) { … }
IHttpActionResult PostOrder(Order order) { … }
IHttpActionResult DeleteOrder(int id) { … }
}
26. ASP.NET Web API cf. MVC
• No views or ActionResult just data or IHttpActionResult
• Data are serialized in JSON or other format (e.g. XML)
• Controllers inherit from ApiController
• No more HttpContext.Current
• View filters
27. ASP.NET Web API - OData
“An open protocol to allow the creation and consumption of queryable and
interoperable RESTful APIs in a simple and standard way”
EnableQueryAttribute
Implements out of the box most of the OData query system: filters, pagination,
projection, etc.
31. ASP.NET 5 – .NET Core
• Totally modular
• Faster development cycle
• Seamless transition from on-premises to cloud
• Choose your editor and tools
• Open-source
• Cross-platform
• Fast
32. ASP.NET 5 cf. ASP.NET 4.X
• No more Web Forms and Web API only MVC
• One ring stack to rule them all, i.e. no more double coding
• Tag helpers – cleaner HTML views
• Project and configuration files in JSON
• Server side and client side packages completelly decoupled
• much more
33. thank you for your attention
stay tuned for next workshops
Andrea Vallotti, ph.D
andrea.vallotti@commitsoftware.it
Notas del editor
1970s – First «implemetation»
1988 – Described as a pattern
several interpretations
mainly used in GUI
clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen
one model – multiple views (even command line)
Given an URL, the routing engine is in charge of:
invoking the correct controller and method (called action);
parsing the parameters contained in it.
By naming convetion routing engine will look for a controller (i.e. a class) named OrdersController;
Then it will look for an action (i.e. a method) named Details;
Routing engine will also try to parse the URL looking for parameter which should be passed to
By naming convetion routing engine will look for a controller (i.e. a class) named OrdersController;
Then it will look for an action (i.e. a method) named Details;
Routing engine will also try to parse the URL looking for parameter which should be passed to
By naming convetion routing engine will look for a controller (i.e. a class) named OrdersController;
Then it will look for an action (i.e. a method) named Details;
Routing engine will also try to parse the URL looking for parameter which should be passed to
Standard way of defining routing convention/pattern;
Several definitions can be added;
Priority based on order;
Segment defaults or optional.
Highly customizable
Integrated with the "standard approach";
What is a controller:
it is a class which derives from Controller class;
it exposes public methods which return ActionResult or subclasses of the latter (see in detail later);
these methods are called actions;
Inside the action usually:
it gets a model and acts on it;
then select a View (by default the view has the same name of the action) and pass to it the model
Other ways to pass data to the View: ViewBag: dynamic, property of the controller
Stateless
As a rule of thumb actions name must be different even if signatures differ otherwise routing is not able to choose the correct method for a given URL
You can have more more methods with the same name by specifing the HTTP method:
AcceptVerbsAttribute
HttpDeleteAttribute
HttpGetAttribute
HttpHeadAttribute
HttpOptionsAttribute
HttpPatchAttribute
HttpPostAttribute
HttpPutAttribute
The Model of MVC is intended to be a "View Model" (example default UserLoginModel)
However also the Business Model can be used
You can use validation attribute to let MVC validate the user input
The Model of MVC is intended to be a "View Model" (example default LoginViewModel)
However also the Business Model can be used
You can use validation attribute to let MVC validate the user input
You can also use attribute to help rendering the view
System.ComponentModel.DataAnnotations
Helper, Bundle, etc.
By default all the views are placed in Views/<controller name>/<action name>.cshtml
Each project can use its preferred View Engine
There are also third-party View Engine which allow to use RoR or Django syntax
Layouts are like master pages in old ASP.NET
Different layouts can be used for different sections of the application (using Layout property)
Strongly-typed using @model directive, dynamic using ViewBag
ViewBag can be used by the View (even in strongly-typed) to pass information to the layout and partial views
Html helper methods can be used to render standard html elements
Helper, Bundle, etc.
Usually action’s return type is ActionResult but you can be more specific using a derived class
DefaultModelBinder creates an empty instance and fills it with values received from client
The default binder can be changed using ModelBinders.Binders.DefaultBinder
We will see a customization example during the demo
Filters are executed in the order listed
Authorization filters are used to implement authentication and authorization for controller actions
You can use an action filter, for instance, to modify the view data that a controller action returns.
Result filters - you might want to modify a view result right before the view is rendered to the browser.
You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
System.Web.Mvc.FilterAttribute base class
WCF – Windows Communication Foundation is mainly aimed to SOAP-based services
ASP.NET MVC relies on IIS (standard or express) while ASP.NET Web API can be self-hosted
Routing - same declaration style, different classes
By default action are matched by HTTP verbs not segment of URL
GET http://www.yoursite.com/api/Orders/5 OrdersController.GetOrder(5)
Data are serialized in JSON or XML based on Accept header of HTTP request
Web API was design to work without a web server (i.e. IIS) and with async framework therefore you should never use HttpContext.Current especially when self-hosted
Web API is responsible to pass the correct context to each operation
Action, Authorization and Exception filters are still available
Basically OData is a way to standardize REST services, e.g. by defining how to filter
It is «simply» an action filter which works with an IQueryable
.NET Core 5:
is the version of .NET that runs on Mac, Windows and Linux;
brings features via packages framework much smaller;
ASP.NET 5 runs both on .NET Framework 4.6 and .NET Core;
Totally modular – cause all the library (such as MVC, file, etc.) have been stripped from the core you have to download them with NuGet
Faster development cycle – simply modify the code and refresh your page, the code will be automatically compiled
Seamless transition – the application runs with its own framework and libraries therefore you do not need to install «special» stuff on the server
Editor and tools – Visual Studio, Visual Studio Code on all platforms but through OmniaSharp also emacs, sublime, etc. are supported. Yeoman generator!!!
Cross-platform – Kestrel is a standalone web server based on libuv (the same as Node.JS),
Fast benchmarks show that ASP.NET 5 is faster than Node.JS
ASP.NET 5 only MVC which contains both old MVC and Web API
One stack one Controller base class, one routing configuration, model binding, etc.
All controllers can have actions which return ActionResult or data
System.Web.* does not exist anymore we have the package Microsoft.AspNet.Mvc
Tag helpers just like angular directive, allows to write more HTML and take advantage of intellisense for CSS and HTML
JSON files no more XML, JSON is easier to understand and widely used
Server/client side NuGet for the server and Bower for the client
Vi rigrazio per l’attenzione e spero di essere riuscito a sintetizzare un argomento che richiede molti approfondimenti.
Qui trovate i miei contatti e sono a disposizione al desk per un veloce incontro per rispondere a tutte le vostre domande.
Grazie ancora e buon forum a tutti.