ASP .NET Core hands-on

40
ASP .NET Core hands-on Andrea Saltarello Enos Recanati

Transcript of ASP .NET Core hands-on

Page 1: ASP .NET Core hands-on

ASP.NETCorehands-onAndreaSaltarelloEnosRecanati

Page 2: ASP .NET Core hands-on

Prossimafermata:AppDay(24/2/2017)

• HTTP,ovvero"Nonavraialcunprotocolloaldifuoridime"(45min)-Speaker:AndreaSaltarello• Xamarin (60min)- Speaker:CorradoCavalli• Implementareilbackend conASP.NET(45min)- Speaker:AndreaSaltarello• Azure API(60min)- Speaker:LorenzoBarbieri• Thenext phase ofUX:conversational (45min)- Speaker:ElisabettaSchiatti• AppePrivacy:aspettispecificidellanormativa,trapresentee(prossimo)futuro(45min)- Speaker:AndreaPalumbo• Moretocome,staytunedJ

Page 3: ASP .NET Core hands-on

Talk.About();

• AnatomiadiunaapplicazioneASP.NETCore• ArchitetturadiASP.NETCore• MVCCore

Page 4: ASP .NET Core hands-on

ASP.NETCoreataglance

Page 5: ASP .NET Core hands-on

LaDev story:glieditorPersviluppare,abbiamovarieopzioni:

1. Supportoper:Sublime,Atom,Emacs,VimeBrackets2. Solosupporto xproj3. macOS:solocsproj;Windows:xproj perv2015,csproj perv2017

Linux macOS WindowsCLI+OmniSharp¹ solo.NETCore solo.NETCore solo.NETCore

Xamarin Studio solo.NETCore²

VisualStudioCode solo.NETCore solo.NETCore X

VisualStudio³ solo.NETCore X

Page 6: ASP .NET Core hands-on

LaDevstory:ildeploy

• (ASP).NETCoreèdistribuitoindueversioni:• LTS:supportateper3anni*o*per1annodopoilrilasciodellaLTSsuccessiva.L’attualeversioneLTSèla1.0.3

• Current:supportate,all’internodellacorrispettivaLTS,per3mesiapartiredalrilasciodella«current»successiva

Sonotuttedisponibiliqui.

• .NETCoreonly:• ildeploy permettesiadiusarel’installazionedelFXalivellodimacchina,siaunalocaleallaapplicazione

• nonesistonodroprelease,tutteleversionisonoinstallateside-by-side

[https://www.microsoft.com/net/core/support ]

Page 7: ASP .NET Core hands-on

AnatomiadiunaapplicazioneASP.NETCore

UnaapplicazioneASP.NETCore:• Può«girare»siasu.NETCoresiasu.NETFramework• Limitatamentea.NETCore,puòesseresviluppatasu:Linux,macOS,Windows• Èuna«normale»applicazioneconsole“ospitata”daunservereconfiguratamediantecodice

Page 8: ASP .NET Core hands-on

demoDevStory

Page 9: ASP .NET Core hands-on

Una«normale»applicazioneConsole…

Page 10: ASP .NET Core hands-on

…ospitatadaunserver…

• Sonoi«container»:ASP.NETCorefornisceiseguenti:• Kestrel(managed,xplat)• WebListener(httpsys,1.1+)

Page 11: ASP .NET Core hands-on

…econfiguratamediantecodice

Perconfigurareunaapplicazioneusiamo:• project.json perspecificarelereference,daVS2017/MacGAinpoiyeolde csproj• Startup.cs (oomologa)perconfigurareimiddleware

1. ConfigureServices()2. Configure()

• [OPT] appsettings.json per«informazioni»diconfigurazione• ASPNETCORE_ENVIRONMENT

Page 12: ASP .NET Core hands-on

Middleware

Sonofunzioni che:• implementanoladelegateRequestDelegate• vengonoaggiuntiallarequest pipelinediASP.NETCoremedianteimetodiMap*,Run eUse*diIApplicationBuilder

publicvoid Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory){

app.Run(async (context)=>{

awaitcontext.Response.WriteAsync("HelloWorld!");});

}

Page 13: ASP .NET Core hands-on

demoMiddleware

Page 14: ASP .NET Core hands-on

Middleware

ASP.NETCorefornisceoutoftheboxalcunimiddleware,traiquali:• Identity• MVC• ResponseCaching (1.1+)• ResponseCompression (1.1+)• Rewrite (1.1+)

Perconvenzione,vengonoregistrati inConfigureServices edattivati inConfigure

[https://blogs.msdn.microsoft.com/webdev/2016/11/16/announcing-asp-net-core-1-1/ ]

Page 15: ASP .NET Core hands-on

MVC

Page 16: ASP .NET Core hands-on

ASP.NETMVCCore

E’ilmiddleware fornitooutoftheboxdaASP.NETCoreperimplementareapplicazionibasatesullavarianteModel2 delpatternMVC(quelladiStruts,Rails,Monorail,…)

APImoltosimileaMVC5diASP.NET4,maconalcunedifferenzestrutturali:• pipelineMVC-WebAPI integrata• supportoacontrollerPOCO• dependency Resolver InjectionPervederloinazione,guardarequi:http://www.ugidotnet.org/video/189329326/NET05--ASP-NET-MVC-Core-1

Page 17: ASP .NET Core hands-on

Talk.About();

• Routing• Navigation Flow

• MVC• Controller• Razor

• Dependency Injection

P.S.:demoscaricabiliqui:http://nsk.codeplex.com

Page 18: ASP .NET Core hands-on

AnatomiadiunURL

DatounoURL,ades:

http://www.sito.net/Customer/Detail/1

Ilrouting engine diASP.NET:• mappaleroute versoaction/file• effettuailparsing delloURLerecuperaiparametri• Puòessereconfiguratopersupportareroute personalizzate

Page 19: ASP .NET Core hands-on

IntroduzioneaASP.NETMVC(1/4)

http://www.sito.net/Customer/Detail/1

Page 20: ASP .NET Core hands-on

IntroduzioneaASP.NETMVC(2/4)

http://www.sito.net/Customer/Detail/1

Page 21: ASP .NET Core hands-on

IntroduzioneaASP.NETMVC(3/4)

http://www.sito.net/Customer/Detail/1

Page 22: ASP .NET Core hands-on

IntroduzioneaASP.NETMVC(4/4)

http://www.sito.net/Customer/Detail/1

Page 23: ASP .NET Core hands-on

Controller

• Unasingola,edopzionale,classebase:Microsoft.AspNet.Mvc.Controller• SonoActiontuttiimetodipubblicidiuncontroller.• Serestituiscono:• IActionResult,il“giro”èquellodiMVC• !=IActionResult,il“giro”èquellodiWebAPI (quindicontentnegotiation oProducesAttribute)

• Secostruiamodeglihelper,decoriamoliconNonActionAttribute

Page 24: ASP .NET Core hands-on

NavigationFlow

Leaction restituisconounvaloreditipoIActionResult.“Pragmapolimorficamente”parlando:

• ViewResult.Restituito dalmetodo View• PartialViewResult.Restituito dalmetodo PartialView• ContentResult.Restituito dalmetodo Content• JsonResult.Restituito dalmetodo Json• EmptyResult.Restituito dalle actionche vogliano restituire “null”• RedirectToRouteResult.Restituito dai metodi RedirectToAction eRedirectToRoute• RedirectResult.Restituito dalmetodo Redirect• YourOwnPersonalResult (semi-citJ);esempi qui equi

Page 25: ASP .NET Core hands-on

demoJSONCustomActionResult

Page 26: ASP .NET Core hands-on

Razor view engine

Razor èilmotoredirendering delleview,che:• Sonofileconestensione.cshtml• ContengonounmixdimarkupecodiceC#• Possonoesseretipizzate

Unaview puòesserevisualizzata:• indipendentemente• all’internodiunlayout• all’internodiun’altraview (Partial View,Editor/Displaytemplate)

All’internodiunaview abbiamoaccessoagliHTMLhelper method

Page 27: ASP .NET Core hands-on

demoLayout

Page 28: ASP .NET Core hands-on

POCOController

Nessunaclassebase;puòessereconvenientedichiarareedattivare:

• IUrlHelperFactory• IActionContextAccessor• publicActionContext ActionContext {get;set;}*• publicViewDataDictionary ViewData {get;set;}*

*Soloconcontainerditerzeparti:• https://github.com/aspnet/Mvc/issues/2151#issuecomment-104541719• https://github.com/aspnet/Announcements/issues/28

Page 29: ASP .NET Core hands-on

demoPOCOController

Page 30: ASP .NET Core hands-on

TagHelper

Sonolaforma“accatiemmellizzata”degliHelper method:• PackageMicrosoft.AspNet.Mvc.TagHelpers (ocmq contenenteclassiderivatedaTagHelper)• @addTagHelper AssemblyName (es:"Microsoft.AspNet.Mvc.TagHelpers")• @removeTagHelper• @tagHelperPrefix• !

PossiamocostruireTagHelper customereditandolaclasseTagHelper

Page 31: ASP .NET Core hands-on

demo_ViewImports.cshtmlCustomTagHelperEnvironment

Page 32: ASP .NET Core hands-on

Display/Editortemplates

IDisplay/Editortemplate:• Permettonodi“insegnare”aRazor comerenderizzare unDataType• Sonopartial view ilcuinomefilecoincideconquellodeldatatype(es:DateTime.cshtml)

Page 33: ASP .NET Core hands-on

demoController(Logger)View (EditorTemplate)

Page 34: ASP .NET Core hands-on

View Component

IView Component:• Sostituisconolechild action diMVC5esonosimiliallepartial view,macompostida:• Una(opiù)view• Un“light”controller

• Siusanocomeglihelper method o,dallaversione1.1diMVCCore,conunasintassitaghelper like• Possonoesseredistribuitiinunalibreriaesternaalprogetto:https://channel9.msdn.com/Series/aspnetmonsters/ASPNET-Monsters-Episode-52-Loading-View-Components-from-a-Class-Library

Page 35: ASP .NET Core hands-on

demoViewComponent

Page 36: ASP .NET Core hands-on

Aree

Page 37: ASP .NET Core hands-on

demoAree

Page 38: ASP .NET Core hands-on

DependencyInjection

• SupportatainController,Filtri,View sostanzialmente*dappertutto*• RegistrareitipiinConfigureServices,indicandoloscope:

• AddInstance• AddSingleton• AddScoped• AddTransient

• Esporreledipendenze• Ctor (Controller,ViewComponent)• Parametriaction:FromServicesAttribute• View:@inject

• E’possibilesostituireilcontainerbuilt inconunoditerzeparti:https://github.com/aspnet/DependencyInjection/blob/dev/README.md

Page 39: ASP .NET Core hands-on

grazie!Feedback:https://it.surveymonkey.com/r/B82FF5RMaterialesu:http://slideshare.net/ugidotnet

Page 40: ASP .NET Core hands-on

Demo

• NSK:http://nsk.codeplex.com• Merp:http://www.github.com/mastreeno/merp