We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

ASP.NET Core 1 (formerly ASP.NET 5): What has changed for MVC and Web API devs?

00:00

Formal Metadata

Title
ASP.NET Core 1 (formerly ASP.NET 5): What has changed for MVC and Web API devs?
Alternative Title
ASP.NET Core 1: What has changed for MVC and Web API developers?
Title of Series
Number of Parts
96
Author
License
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
The revamped ASP.NET vNext will do away with duplications in the ASP.NET family's individual frameworks and, by doing so, will combine MVC, Web API and web pages[c1] within ASP.NET MVC 6. It is clear to see that this cannot be achieved without breaking changes. This session will detail all the relative changes as well as the new possibilities that MVC will offer.
SoftwareJava appletSoftware framework.NET FrameworkServer (computing)Application service providerCore dumpContent (media)Bootstrap aggregatingMobile appCompilerInterior (topology)Computing platformPhysical systemCache (computing)Configuration spaceCore dumpApplication service provider.NET FrameworkServer (computing)Content (media)MathematicsMereologyComputing platformLevel (video gaming)Physical systemConfiguration spaceCross-platformWindowSoftware frameworkSlide ruleAdditionRepository (publishing)Software developerMultiplication signSampling (statistics)Cartesian coordinate systemWritingLibrary (computing)CASE <Informatik>Information technology consultingINTEGRALClient (computing)Modal logicWorld Wide Web ConsortiumSystem administratorWeb applicationCodeFlow separationInstance (computer science)Semiconductor memoryTheoryData centerPoint cloudReverse engineeringProxy serverForcing (mathematics)Latent heatInformation securityDifferent (Kate Ryan album)CausalitySoftwareRevision controlCodeComputer configurationAuthenticationIntegrated development environmentAbstractionDependent and independent variablesBitControl flowProduct (business)Form (programming)2 (number)Software bugRoutingCellular automatonInternet service providerWeb 2.0Computer animation
Software.NET FrameworkApplication service providerCore dumpHome pageGame controllerView (database)Uniform convergenceRoutingDigital filterHuman migrationCodeSoftware frameworkRevision controlElectric currentForm (programming)Bootstrap aggregatingDependent and independent variablesComponent-based software engineeringProcess (computing)Configuration spaceInternet service providerIntegrated development environmentOvalProduct (business)Adaptive behaviorBit rateDoubling the cubeArithmetic mean.NET FrameworkComputer filePlanningCodeCartesian coordinate systemExtension (kinesiology)Instance (computer science)Social classImage resolutionConnectivity (graph theory)Object (grammar)CASE <Informatik>Software maintenanceAxiom of choiceEncryptionMiddlewareData compressionException handlingInformation securityVariable (mathematics)Game controllerView (database)Endliche ModelltheorieInjektivitätUniformer RaumInternet service providerSoftware frameworkWindowProcess (computing)Object-oriented programmingError messageWeb pageOcean currentCodeComputer programmingRevision controlInformationComputing platformGeneric programmingForm (programming)Hacker (term)Server (computing)AdditionGoodness of fitFluid staticsConfiguration spaceCore dumpWorld Wide Web ConsortiumWeb applicationTask (computing)Integrated development environmentDependent and independent variablesHome pageSoftware developerApplication service providerWeb 2.0Link (knot theory)Default (computer science)Communications protocolSocket-SchnittstelleVisualization (computer graphics)Computer animation
BefehlsprozessorConfiguration spaceMaxima and minimaConvex hullDuality (mathematics)Computing platformIdentity managementRevision controlPhysical systemInformationBuildingMenu (computing)RankingLine (geometry)Link (knot theory)Data structureComputer fileInformation overloadConfiguration spaceSource codeCore dumpApplication service providerSet (mathematics)AdditionObject (grammar)Variable (mathematics)Integrated development environmentWorld Wide Web ConsortiumConnected spaceString (computer science)Constructor (object-oriented programming)Software testingEmailSocial classPasswordSoftware developerFlow separationDifferent (Kate Ryan album)Factory (trading post)DatabaseArithmetic meanMobile appServer (computing)Default (computer science)Product (business)Revision controlCASE <Informatik>Line (geometry)Instance (computer science)Web applicationMetropolitan area networkRight angleComputer animation
Configuration spaceBuildingMenu (computing)Internet service providerOvalConvex hullFactory (trading post)Maxima and minimaBefehlsprozessorSoftware developerDefault (computer science)Physical systemInformationLink (knot theory)Computing platformHTTP cookieCore dumpIdentity managementRevision controlHome pageSoftware frameworkAuthenticationServer (computing)Chemical equationSpacetimeSoftware repositoryGame controllerPrice indexView (database)Electronic mailing listSet (mathematics)Virtual machineCASE <Informatik>Multiplication signSummierbarkeitCausalityPasswordGroup actionInterface (computing)Design by contractGame controllerUniform resource locatorDefault (computer science)Revision controlLevel (video gaming)InjektivitätAxiom of choiceHookingCartesian coordinate systemInstance (computer science)System administratorMechanism designCellular automatonRepository (publishing)View (database)Video game consoleInternet service providerBranch (computer science)MiddlewareFAQCurveArithmetic meanAdditionSoftware frameworkInformationException handlingDatabaseMobile appSheaf (mathematics)Computer fileHome pageConnected spaceVisualization (computer graphics)RoutingWeb browserSocial classError messageConstructor (object-oriented programming)Projective planeProduct (business)Travelling salesman problemImplementationBitConfiguration spaceLogic gateInheritance (object-oriented programming)Integrated development environmentKnowledge-based configurationFactory (trading post)Connectivity (graph theory)Physical systemLocal ringWorld Wide Web ConsortiumCore dumpSoftware developerCross-platformApplication service providerWindowLink (knot theory)Flow separationFluid staticsClosed setSemiconductor memory.NET FrameworkMereologyWeb 2.0MappingPoint (geometry)Control flowComputer clusterComputer animation
Software repositoryPrice indexView (database)Menu (computing)BefehlsprozessorComputer programOvalFluid staticsMaxima and minimaWebsiteServer (computing)Ocean currentINTEGRALApplication service providerCartesian coordinate systemCore dumpSocial classRight angleVideo game consoleWorld Wide Web ConsortiumBitVirtual machineoutputInstance (computer science)Game controllerCodeSoftware frameworkComputer programmingField (computer science)WordCategory of beingInformationMessage passingArithmetic meanCASE <Informatik>2 (number)Goodness of fitBookmark (World Wide Web)Computer animation
Computer programFluid staticsOvalDisintegrationConvex hullMaxima and minimaDemo (music)SoftwareMach's principleApplication service provider.NET FrameworkEndliche ModelltheorieData modelWorld Wide Web ConsortiumCore dumpDifferent (Kate Ryan album)Revision controlGroup actionWeb applicationView (database)Application service providerMereologyOcean currentWeb 2.0Level (video gaming)Right angleElement (mathematics)Arithmetic meanHookingLogicHyperlinkLatent heatAdditionSocial classParameter (computer programming)Direction (geometry)NamespaceLine (geometry)Core dumpJava appletInjektivitätCodeWordComputer fileWorld Wide Web ConsortiumAttribute grammarSoftware frameworkBus (computing)Diffuser (automotive)DecimalCodeServer (computing)Instance (computer science)Game controllerBootingMathematicsConfiguration spaceComputer animation
Uniform resource locatorParameter (computer programming)Core dumpGroup actionSoftwareGame controllerAttribute grammarString (computer science)OvalGame controllerGroup actionElectronic mailing listParameter (computer programming)Uniform resource locatorAddition1 (number)Attribute grammarContent (media)Ocean currentRoutingString (computer science)Free variables and bound variablesCASE <Informatik>Multiplication signArithmetic meanConnectivity (graph theory)Web 2.0Application service providerWorld Wide Web ConsortiumCartesian coordinate systemInjektivitätQuery languageSimulationMereologyFlow separationFile formatSystem callInstance (computer science)Time zoneCodeInternet service providerPoisson-KlammerCore dumpComputer animation
Attribute grammarGame controllerString (computer science)OvalSpacetimeSoftware repositoryBefehlsprozessorInformation managementMetropolitan area networkElectronic mailing listMenu (computing)InjektivitätWorld Wide Web ConsortiumInheritance (object-oriented programming)Goodness of fitRouting2 (number)Latent heatAdditionGame controllerWeb 2.0Computer animation
MathematicsSoftware repositoryString (computer science)Menu (computing)Content (media)Data typeServer (computing).NET FrameworkLengthLeast squaresVacuumGamma functionFinite element methodExecution unitNumberRandom numberMaizeConvex hullDrum memoryLemma (mathematics)Maxima and minimaBefehlsprozessorApplication service providerPhysical systemTask (computing)Interface (computing)Context awarenessDependent and independent variablesEmailEmailCodePlanningGroup actionPerfect groupUniform resource locatorCASE <Informatik>Goodness of fitAdditionContext awarenessObject (grammar)Interface (computing)Different (Kate Ryan album)SubsetOcean currentResultantDependent and independent variablesParameter (computer programming)RoutingMultiplication signElectronic mailing listServer (computing)Application service providerWorld Wide Web ConsortiumCategory of beingSoftware frameworkBitStreaming mediaLogicVirtual machineArithmetic mean2 (number)Type theoryPoint (geometry)TransmitterError messageCodeSoftware developerGradientInstance (computer science)Web 2.0System callComputer animation
String (computer science)OvalAttribute grammarGame controllerInternet service providerSoftwareComputer configurationInstance (computer science)Default (computer science)Internet service providerFile formatParsingConfiguration spaceHookingInjektivitätAdditionForm (programming)outputApplication service providerFunction (mathematics)Multiplication signDesign by contractSerial portSocial classComputer animation
Configuration spaceInternet service providerOvalConvex hullComputer configurationRun time (program lifecycle phase)RootRepository (publishing)File formatDigital filterOpticsMaxima and minimaBefehlsprozessorTwin primeMenu (computing)Normed vector spaceFunction (mathematics)SerializabilitySocial classCASE <Informatik>Moving averageSet (mathematics)File formatInstance (computer science)Hydraulic jumpSerial portComputer configurationSoftware framework.NET FrameworkEndliche ModelltheorieFilter <Stochastik>outputRevision controlMappingAdditionKeyboard shortcutDesign by contractGroup actionComputer animation
Computing platformSoftwareRevision controlLevel (video gaming)Electric currentModemEmailTwitterSoftware frameworkConfiguration spacePhysical systemLevel (video gaming)Revision controlAdditionSoftware developerComputing platformApplication service providerMereologyCore dumpCartesian coordinate systemWeb 2.0Semiconductor memory.NET FrameworkSystem administratorComputer animation
Transcript: English(auto-generated)
Okay, hello everybody. Let's get started. Welcome to this talk about ASP.NET Core 1. I am Manfred. I am a trainer and a consultant, and I'm focusing on Angular at the client side as well as on server-side.net.
I live in Austria and I also work in Germany, and from time to time I am visiting customers in other parts of the union or of other parts of Europe. So what is the goal of this talk? The goal of this talk is to give an overview of changes for MVC and Web API developers regarding ASP.NET Core.
I will use slides for this, and in addition to that I have prepared a sample. So what are the contents? I will first of all give an overview of Core 1, and then I want to talk about bootstrapping,
how to bootstrap an ASP.NET Core application within your web server. And then I want to talk about web apps, web apps that are created with MVC,
and then I will talk about web APIs that can also be created with MVC. So let's start with the overview. Here we see a graphic that has been painted by Scott Hanselman some time ago, and I think this graphic really nicely shows what .NET Core is about.
It shows that this new .NET Core is a cross-platform solution, and cross-platform doesn't just mean Windows 8, Windows 8.1, and Windows 10. No, it also means that you can run .NET Core on Linux or on Mac computers.
And ASP.NET Core 1 is leveraging .NET Core, so you can write web applications with ASP.NET Core 1 that can run at any platform you see here. But if you want, you can also use the traditional .NET framework beneath ASP.NET Core 1.
So in this case, you can use all the libraries you have, all the libraries you have written for the traditional .NET framework, but in this case, you are restricted to the Windows platform. The new .NET Core and the new ASP.NET Core bring some advantages.
As mentioned, you have a cross-platform solution. In addition to that, you have a very lightweight solution that bases upon NuGet packages. The whole .NET Core framework consists of NuGet packages,
and you just have to use the NuGet packages you want to use, you need for your application. So when you want to use data access, just pull the data access packages out of the repository. When you don't need data access, then you can leave those NuGet packages.
So you just go with the parts of the .NET framework you need, and this leads to very lightweight solutions, and this also leads to a side-by-side deployment. So .NET Core gives you the possibility to deploy your part of the .NET Core framework
as part of your application. So you don't demand an administrator to install the .NET version you need. You can just ship the necessary parts of .NET as an integrated part of your solution. That is quite nice, and this is quite important in this world
where we are running more and more our software in data centers or in the cloud, my cloud, your cloud, you know. .NET Core is also about self-hosting. You can self-host your ASP.NET Core solution
so you don't need a heavyweight web server like IIS or something else. And you have something I want to call the F5 compile to memory experience. So let's assume you've made a bug within your application.
Then you can just alter the code and press F5, and then ASP.NET will automatically recompile your code into the memory, and then you can, in theory, immediately see what your bug fix has done,
whether your bug fix worked or not. When it comes to hosting, you have several options. For instance, you could use Kestrel for hosting. Kestrel is this new lightweight, very fast cross-platform web server that has been written by the ASP.NET team.
It is intended for self-hosting scenarios. There is also another hosting solution that is called the WebListener. The WebListener is a Windows-specific self-hosting solution that provides Windows-specific features like Windows authentication.
When you want to go with IIS, then you are running ASP.NET outside of IIS. Then you are just using IIS as some kind of facade, of some kind of reverse proxy, and this facade is just delegating some user requests to a Kestrel server
or to some other server behind. That brings several advantages. First of all, you can use IIS for what it was intended for. You can use IIS to communicate with a lot of users that are there outside of your company.
And in addition to that, you can use Kestrel as a container for your ASP.NET applications. You can use Kestrel so that your ASP.NET application is behaving the same way all the time.
So it doesn't matter whether your application runs within Kestrel or with IIS. It always behaves the same because it is always executed within the same execution environment. That wasn't the case in former versions of ASP.NET,
and this led to several difficulties. For instance, to a slightly different behavior, for instance, when it came to security. In these cases, your applications might act differently when they are running within a cell first. This issue is gone now.
Now ASP.NET always runs in the same execution environment. And the same holds true when you are using some other web server, for instance, NGNext on Linux. In this case, you are using NGNext to communicate with all the users out there.
NGNext acts as some kind of facade, and this facade is delegating to some other execution environment behind of it, for instance, to the cross-platform solution Kestrel. So why do we need a new ASP.NET for all this?
Why do we need the new ASP.NET core? One solution, one answer to this question is that the old ASP.NET frameworks were very tightly coupled to IIS. They have been very tightly coupled to something that is called System Web, and System Web is very tightly coupled to IIS.
It is especially true when it comes to web forms and also when it comes to ASP.NET MVC. And so we had to get rid of System Web to get some kind of loosely coupling between ASP.NET
and IIS or the web server that is used to run ASP.NET. So as they just tried to get rid of System Web, they had to re-implement all the features that System Web provides.
And these features are about low-level stuff, low-level stuff we all know, low-level stuff like session handling, low-level stuff like caching, configuration, or routing. System Web also cares about bootstrapping ASP.NET within the web server.
It also cares about the HTTP abstractions, about dealing with HTTP requests and responses. So all this stuff had to be re-implemented. And the consequence of this is that we are facing some breaking changes
when it comes to those low-level APIs. As there are breaking changes, the product team at Microsoft used this to just tidy up the framework a bit. When you look at this ASP.NET-related frameworks today,
at frameworks like Web API or MVC or web pages, then you are seeing some doublings. For instance, there are two controller concepts, two controller concepts that are quite the same but slightly different,
one for MVC and one for Web API. And the same holds true for other concepts like filter, like the model binder, like routing, like dependency resolution, and so on and so on. So there are some couplings when you look at these frameworks. And the same holds true when you look at MVC and web pages.
There is also a doubling, namely the razor fuse. And the product team tried to get rid of these doublings. They tried to get rid of all those concepts, and therefore they created MVC Core 1, which is just a unification of MVC, of Web API,
and it will also include the features of web pages in future. The web pages features aren't there yet, but they will come. And so you have uniform concepts for controllers, for views, and so on.
So you don't have an own controller concept for the world of Web API and the own concept for the world of MVC. I think that is quite nice. So what does that mean for migrating to .NET Core?
This just means that your code needs adaptation when you want to migrate to .NET Core. Your code won't run with .NET Core without any modifications. But you don't need to hurry, because the current framework versions will be maintained.
Saying that WCF and web forms won't be migrated to Core, at least there are any plans for this yet, but you don't need to hurry when you're using these technologies, because these technologies are here and they stay here. They will be available on the traditional .NET 4 platform,
but as mentioned, they won't be migrated to .NET Core. And there will be some maintenance. When it comes to web forms, web forms have seen some new features in the last month.
So let's talk about bootstrapping ASP.NET Core 1. What do we need to get ASP.NET Core 1 up and running within the web server of your choice? First of all, you must know that ASP.NET Core brings a middleware concept,
a middleware concept that is quite similar to the concept of OWIN, who has used OWIN before. I think most of you about a third. It seems OWIN just defines a host process, and so does the middleware concept of ASP.NET Core.
And this host concept, this host process is just running a server component. This server component is communicating with the outside world. It is communicating by the means of HDB and HTTPS. And this server component is just taking the incoming requests
and pulling them through a pipeline that consists of middleware components. And these middleware components can do stuff with these incoming requests. They can care about security scenarios. They can care about encryption and decryption.
Those middleware components can care about compression and decompression. They can implement some web protocols like cores or like web sockets and so on and so on. Some middleware components will just deliver some static files,
and other middleware components will also delegate to a web application framework, a web application framework like ASP.NET MVC. And, of course, the web application framework will delegate to your application code.
And then your application code runs. It performs some tasks, and the response from your application code is again pulled through this pipeline, through this pipeline that consists of middleware components. And at the end, the server is sending the response back to the caller.
So bootstrapping your ASP.NET application is all about setting up this pipeline, this pipeline of middleware components. And for this, you are using a class that is called startup by convention.
And this class has also a method that is called configure. And this configure method is getting an application builder. And this application builder is where you are setting up your middleware components. You are just executing some extension method on this object
to define the middleware components you want to use. In this simple case, I am just registering one middleware component that is delivering static files to the user, static files like HTML files or MHS or CSS or JavaScript files.
And then here I am registering the MVC component, and this MVC component is delegating to ASP.NET MVC at the end of this pipeline.
You can also create a configuration considering the current execution environment. In this simple example, I am just grabbing the hosting environment variable by the means of injection. And then I am using this variable to find out the current environment my application runs in.
When I am running within a development environment, then I am setting up the developer exception page. This developer exception page is just another middleware component, and this middleware is displaying a nice exception page
with a huge amount of information about your exception when an exception occurs. So this is exactly what I want to know when I do a mistake during programming. But that is not something I want to have within a production environment,
because as you might know, it is not a good idea to expose too much exception information within a production environment that would give a hacker too much valuable information about how to refine the attack.
So when I am just within a production environment, I am using this exception handler here. The exception handler is just redirecting the user to some page that is displaying some generic error message, something like, oops, there was a mistake, oops, there was an error, something went wrong.
So the question here is, how can ASP.NET find out about your current hosting environment? And the answer to this is quite simple. ASP.NET is just looking at some environment variables. And when those environment variables are set to development,
then ASP.NET assumes that you are running it within a development environment. So it is good that Visual Studio is just setting these environment variables for us, so we don't have to care about this.
In addition to that, the new ASP.NET core is about dependency injection, or to cite an old techno song from the 90s, D-I-D-I everywhere.
D-I is really baked into the framework, and you have this method called configure services within your startup class that you can use to set up all the services for your D-I container. So in this case, I'm just using the convenience method at MVC.
And this convenience method just registers the default services, the default classes and objects for ASP.NET MVC. You don't need to do this. You can also use this method to register your own services for ASP.NET MVC.
And by doing so, you can adopt the behavior of ASP.NET MVC. You can alter, you can modify the behavior of this framework just by switching out the used services. So let's look at a demonstration for this.
Here I have a very simple ASP.NET core web application, and here I have my startup class. And the startup class has a constructor.
The constructor gets the hosting environment injected, and then I'm using a configuration builder here. The configuration builder is some kind of factory or let's say builder that is used to create a configuration object, a configuration object that allows you to read some configuration data
out of several different configuration sources. In this case, I'm just claiming that I want to use JSON. JSON is the new XML, and so I want to use JSON to read some configuration settings.
I'm reading two JSON files here. The first one is called app settings JSON, and the second one is called app settings environment name JSON. For instance, app settings production JSON, app settings development JSON. Both of these files are optional, so they don't need to exist.
And when we have a look into this JSON file, we will see that this JSON file is very simple structured. This is the wrong JSON file. This one isn't simply structured, but my eyes are leaving me here. We have the right one. We see that this JSON file is quite simply structured.
So you don't have to go with this overloaded web config anymore. This overloaded web config with thousands and thousands of entries. You just have a very slim configuration file that just consists of the configuration settings you need.
There is even support for other sources of configuration files. For instance, you could load some kind of XML file here, or if you like the 90s, you could also load some kind of any files here. In addition to that, I'm loading all the environment variables into my configuration builder.
So I can use environment variables to shadow my configuration settings. That can be especially useful when you are trying out different configurations on the fly.
And then at the end of this, I'm just building a configuration object out of my configured configuration builder. And this configuration object I'm using here to just fetch a connection string. I'm fetching the connection string, connection strings column, default connection,
which is defined directly here. There is another nice feature that is called user secrets. User secrets are just configuration settings that you don't want to check into your source control.
For instance, these settings can be about your personal passwords. You are just using for testing purpose, your personal email server. All these settings can also be about your personal database you are using for development.
When you want to use these user secrets, then you are just adding the user secrets to your configuration builder by the means of this method here. And then you are jumping to the command line and there you have some kind of nostalgic user experience.
And this nostalgic user experience gives you some command line interface to list all your user settings that are installed on your machine. Here in this case, I have two user settings, my very secret password,
which is none of your business and a variable X that is Y. And after doing so, you can also read this local, this machine local settings that you don't want to check in. So this is just a constructor of my startup class.
And this constructor is using the new configuration system here. In addition to that, of course, the startup class has several other methods. For instance, here I have the method configure services
and this is where my dependency injection container is built up. This is where some services are registered for my dependency injection mechanism. Saying that, asp.net brings its own dependency injection container, but if you want, you can just hook in the dependency injection solution of your choice.
There are hooks for that and so you can use something like auto-fuck and so on to get up and running. In this case, I'm just using the ordinary built-in container with the default services for asp.net MVC.
Then here I have my configure method. This is the method that is building up the pipeline, the pipeline that consists of middleware components. And this method just gets the application builder by the means of injection.
It gets the current hosting environment and it gets a logger factory. And here I'm setting up this logger factory. I'm just claiming that I want to lock down to the console and I'm claiming that I want to configure the console logger with some section of my configuration file.
When you remember my app settings configuration file, then you are also remembering this section here that is configuring my logger. So I also want to have debug information, for instance.
Then I'm checking whether I'm running within a development environment. In this case, I'm setting up the developer exception page, I've told before. Then I'm setting up a database error page that is just displaying some additional information when a database exception occurs.
And here would be the right place to set up browser link to connect Visual Studio to your browser in your development environment. For the production environment, I'm just using the exception handler. Then I'm also setting up the middleware for delivering static files
and I'm setting up the middleware which is delegating to MVC. And by doing so, I'm setting up a default route. A default route you all might know when you have used MVC or Web API before. A default route that just maps all the action methods
of your controllers to this URL here. So in addition to this startup class, there is another file that's called the project.json file. And this is where all your naget packages are mentioned.
All the naget packages you have downloaded. Don't get used too much to it because this project.json file will disappear in future. The product team decided that they want to phase out this file more and more.
And at the end of the day, they want just to give you some kind of project file like the project files you know from traditional Visual Studio solutions. And this project file could also mention all the things you've downloaded from naget. They are just designing this stuff
and so we will go with this project.json file for a while now. But at some point in future, it will disappear. So let's have a look at the controller. Here we see that the high level API hasn't changed much
when you compare it to MVC5 or MVC4 or other versions of MVC and Web API. You just have an ordinary class and this class is deriving from controller. Saying that, you don't need to derive from controller anymore
when you don't need the features that the controller base class provides, then you can just skip the inheritance of this class. That means everything can be a controller nowadays that also holds true for an ordinary class that isn't subclassing anything.
Then my controller has some constructor and this constructor is taking a flight repository by the means of dependency injection. And then I have some action methods that are mapped to URLs
by the means of the route I've set up before and those action methods are just calling the repository to deal with data and then they are delegating to some view. As you see here, not much has changed. This really looks like the good old stuff we know
from the old world of ASP.NET MVC5 and so on. To make dependency injection happen, we have of course to configure our dependency injection container. In this case here, I have to tell the dependency injection container
which instance to inject here, which implementation of this interface to inject here when the home controller is created. And for this, I'm switching back to the startup class. I'm switching back to configure services
and here I'm using services at transition. I want to use for the interface a flight repository, just the flight entity framework repository, which is a very lightweight repository I've written with ASP,
not ASP, with Entity Framework Core 1 before. So let's start this and let's put in a break point here
that lasts a bit now. So let's cross fingers. You will make it come on.
Yeah, here we go. And we see that ASP.NET is really injecting my flight entity framework repository into the constructor of the home controller and then you should see some page.
Yeah, awesome. You can also inject some kind of logger in your controller. For instance, here I'm injecting a logger of home controller.
That means that home controller is just a category name for the locked messages. And then I'm using this logger here. Logger log debug. Manfred was here and you've been hacked.
And now there is my favorite word I've just learned this week. So let me try to write it.
I think this word is quite international and I've checked it before. It totally aligns to the current code of contact here at the conference. Okay, so in this case I will just log out some information by the means of this logging framework I've set up before.
Let's keep this in mind for the next demonstration. Of course, as I mentioned before, ASP.NET Core is nowadays running outside of IIS. IIS is just a facade for my ASP.NET application
and saying that I also have to say that my ASP.NET Core application is just some kind of console application. Yes, you've heard right. It's just some kind of console application. Perhaps you've seen it. I have a program class here,
a good old program class with a main method. And this main method is just setting up a web server that is running behind IIS, a web server that is using Kestrel, a web server that is using IIS integration to get all the data from IIS,
for instance, data about the current user. And I'm using the startup class to configure my pipeline and then I'm running my solution here. Because of this, of course, I can very easily run my application stand alone
without IIS in a very lightweight manner. So let's do this. It takes a while. It takes a bit on this machine to get up and running with this server. So I'm thinking the server comes slowly up here
within this console. And yeah, here we have our logging information. Manfred was here. Great. And here we have our website running on what, 5,000.
So as you've seen here, there is not a big difference between self-hosting and hosted solutions as it was in the past. Awesome. Okay.
So there is another nice feature when it comes to web applications with ASP.NET Core. And this feature is called deck helper. Before I want to talk about deck helpers, let's talk about those HTML helpers we all got used to.
HTML helpers in ASP.NET MVC 5 and 4 and 3 and so on are just methods that are called within your view. And for me, this always felt a bit strange. Calling a method within a view
just doesn't feel right for me. Although it's about view logic, it doesn't feel right. In the past, I think about 15 years ago, I've used server-side Java. Don't tell anyone. I was young and needed the money. And I didn't know better then.
But server-side Java has a very nice feature. Server-side Java allows for the execution of text, of HTML elements on the server-side. And so it is quite natural to hook in some view logic into your views.
And guess what? ASP.NET Core 1 is just providing the same feature nowadays. It provides a feature called deck helper, and deck helper is exactly that. A deck helper is just a HTML element and or an HTML attribute that is executed server-side.
So by the means of a deck helper, I'm just setting up a hyperlink here, a hyperlink that points to a specific controller, a hyperlink that points to a specific action method within this controller, and the hyperlink that is passing the parameter ID
with the value one to this action method. So this feels quite more natural than calling some methods within the views. And in addition to that, it is very easy to write your own deck helpers. Just subclass some abstract class the framework provides.
Just write in some lines of code. Just override some methods, and you have your own deck helpers for your own features. To make use of deck helpers, you have to register them.
For this, you can use this directive on the top of your Razor view. This directive is called add deck helper, and here I'm importing all the deck helpers. Star means all the deck helpers of this namespace here,
or let's say of this assembly here. And when you don't want to repeat this line of code ever and ever again, you can just place it within the file underscore view imports. The new underscore view imports file is just a piece of a view,
a piece of a view that gets respected for every view that is rendered. So just place it here to get some global experience. So much for web apps within ASP.NET Core 1.
You've seen that dependency injection is baked into it. You've seen this pipeline concept. You've seen that the low level APIs change dramatically, things like logging, things like configuration, but you've also seen that the high level APIs
are quite the same. They really don't change much. So let's talk about web APIs. When it comes to web APIs in MVC Core 1, then you must know that there is not an own routing concept for web APIs. You just have to go with the same routing concept
you are facing in the world of MVC. In the past, there was an own routing concept for ASP.NET Web API. This routing concept was quite similar to the concept of MVC, but it was not the same concept.
For instance, this former concept of ASP.NET Web API allowed you to define the HTTP verb by a convention. When you had some methods that were starting with the word get, then Web API notes that you want to call this method
via the HTTP verb get, and the same holds true for post and for put and for delete. You just use this convention to show Web API which HTTP verb the current action method is intended for. This convention has come. This convention has never been part of MVC.
And as we are facing a unified framework, a new version of MVC that is also a new version of Web API, we just have to forget about those conventions. And in addition to that,
routing doesn't even consider URL parameters to select the action method. That was also a feature of the routing within ASP.NET Web API. With ASP.NET Web API, you could have ended up with one URL that's pointed to several methods.
And in this case, Web API just looked at the URL parameter to decide for one or for the other method. Also, this has never been a part of MVC, and that is why also this feature has been done. So to put it in a nutshell,
you have to align with all the routing features of the world from MVC. But when you want to migrate pre-existing code, then you can use this component here, the Web API combat shim. This shim mimics the traditional behavior of ASP.NET MVC,
of ASP.NET Web API within MVC Core 1. So when you are using this component, then this component is just switching out some dependencies of MVC
by the means of dependency injection. Some services are switched out, and then MVC behaves quite like ASP.NET Web API in the past. As the name suggests here, this is just intended for upgrading your stuff. It is not intended for writing new code.
It's just a shim. So the best thing to start with routing and Web APIs in MVC Core 1 is to leverage attribute-based routes.
With these routes, you can mimic the behavior of traditional Web API applications. In this case, I'm using the route attribute to define a route prefix that is called API controller, where controller within parenthesis is just a placeholder.
This name controller within the brackets is just a placeholder for the name of your controller. In this case, the name is flight, not flight controller. The suffix controller is omitted. The name here is flight, and this name will be put into this controller placeholder.
And in addition to that, I have several action methods here, getByID, which takes an ID and returns a flight, getByRoute, which takes from and to and returns a list of flights, I also have postFlight, which takes a flight and returns exactly nothing, white.
And when it comes to getByID, I'm using HTTP get, and HTTP get is doing two things here. It is just configuring this method for the usage over the verb get, and in addition to that, it defines an additional route segment.
So in this case, the whole URL that is pointing to this method is just called API flight, my route prefix, plus ID. And here again, ID is a placeholder, a placeholder that defines some value for the parameter with the same name.
So when I'm calling API flight 17, then the value 17 is passed to this method here. The same holds true for the next method. Here I'm using the route segment by route.
This isn't really RESTful, please. I'm sorry for this, but I don't think it has to be RESTful all the time. And as I'm not specifying placeholders for these parameters here, you just have to mention these parameters within your URL
by the means of the query string. And in addition to that, the same is, of course, true for this post method here. This post method is dedicated to post calls. One important thing here is that you have to use this from body attribute
when you want to read some object out of the content of your current HTTP request when you want to read the body of your HTTP request. This is really mandatory. Only when you are using from body, ASP.NET MVC Core 1 kicks on the formatter feature, the formatter pipeline.
This formatter pipeline consists of several formatters that are able to serialize and deserialize several data formats.
For instance, JSON or XML or so on. So let's look at a demonstration for this. Here I have a very simple web API. You see there is no on base class for web APIs.
I'm just using the good old controller base class that comes with MVC. Here I have my route prefix. I'm using dependency injection once again. And here I am having my methods that are dedicated to specific HTTP verbs
and that are defining some additional route segments. So let's just put some breakpoints in here. Get all and find by AD and post. And let's start this.
No. Let's start it within IIS. Let's do self hosting. I'm starting it up within IIS or let's say behind IIS.
So you see my machine here is very fast. It was a great investment. And here I have Fiddler to communicate with my web API. Here we go. And now I want to call API flight.
And so my get all method is called. And this method is returning a list of flights by the means of JSON. Here we have our JSON document. Let's append an ID. In this case, the other method is called that takes the ID within the URL.
And this ID is passed to this parameter here. So I think that isn't that awesome. We've seen such stuff before. But let's do something different. Let's request XML.
That is something that worked when we went with ASP.NET web API. We just were able to transmit the accept header with XML. I'm executing this here. And I'm getting JSON back.
So at this point, I just want to cite the famous philosopher, Mick Jagger, who said you can't always get what you want. And I think that is especially true in this case here. The reason for that is that while XML was a huge thing about 10 years ago,
it's some kind of special interest today. And so XML support isn't directly built into ASP.NET MVC. There is a nuget package for it. And you can load this nuget package. And you can activate the support for XML that is located within this nuget package.
When you do so, then you get back the good old XML support. I will do this after that. So just let's keep this in mind. So here I'm taking my JSON I've got.
And I'm sending this JSON up to the server. I want just to create a new flight. The new flight doesn't have bookings.
It doesn't have an ID. And it shall go from Oslo to Graz, where I'm living in. And it should go tomorrow, although there are some plans to put down the work.
And of course, I have to mention the content type of this stuff, text JSON. So that didn't work. Oh, yeah.
Thank you for this. Now it works. Perfect. The JSON is passed out of the body. And here I have my flight object. The flight object that just has been deserialized out of the body. That all works perfectly.
But we are getting the status code 200. And when you are a humble HTTP developer, then 200 is completely OK. But when you are a friend of REST, then 200 isn't. Because in this case, you just want to get the 201 status code that is telling you that something has been created.
And in addition to that, you will likely want to have some header that points to the URL, which is the URL of this saved object here. So what I want to do here is I just want to influence the created header,
the created status code, and the created header entries here. And for this, I'm switching back to my post method. And here I'm just returning an I action result.
And there are some action results baked into the framework. And there are some convenience methods for those action results. For instance, there is the action result created at action, or the convenience method created at action. And this method creates an action result that has the 201 status code within it.
In addition to that, it points to the URL of some action method. Here it is the URL of the action method getByID. You might remember the route for this action method was API flight ID,
where ID was a parameter. And for this parameter, I'm defining some value, for instance, 17. So this means that exactly this value is posted to the caller
to inform the caller about the current URL of the saved object. And in addition of that, I'm also sending back the whole flight object here. So let's try this.
Let's start up. I've just seen the timing here is quite well.
And let's create another flight, created at action is called. And now we get the 201 status code. And we are getting this location header here.
So for some situations, there are already predefined action results. But of course, you can also create your own action result by implementing this IActionResult interface. It just comes with a method called executeResultAsync.
And this method gets an action context. And this context brings you the current request object and the current response object. And with these objects, you can just define your answer for the caller. I've done this here. Here I've created an accepted action result.
It is just implementing this IActionResult interface. And within the execute method, it is grabbing the request object. It is grabbing the response object. It is setting the status code to 202, which means accepted. It is setting some user-defined header.
And that's it. When you write something down to the body, you can just use the property body of the response. The body is just a stream you can use to write down some bytes or some other stuff.
So it is quite easy to implement your own logic here if you've seen. So let's talk a bit about configuring ASP.NET MVC.
ASP.NET MVC has this at MVC convenience method we've used before. This method just adds all the default services for MVC to the dependency injection container. And in addition to that, you can proceed with some other methods like at JSON options or at MVC options.
And this is where you can create a configuration for MVC. For instance, this is where you can hook in additional formatters. For instance, formatters for XML parsing.
And those formatters for XML parsing are located within this NuGet package. These classes are said to be nominated for the largest class name contest this year. The first class is called, let's take a brief, XML data contract serializer input formatter.
And the other one is the XML data contract serializer output formatter. So just try to say that three times very quickly. And when you are hooking up them, then you will get JSON, not JSON, then you'll get XML support.
So let me just show you that. Let's jump into the startup class here we have at MVC. Then I can proceed with JSON options here. I can configure my JSON serializer options, start serializer settings.
Here I can do all the stuff you know from JSON.net. I can configure the data handling and so on. I can also configure the formatting. For instance, here I'm saying I want to have pretty printed intended JSON. And in addition to that, I can call at MVC options to configure my MVC framework.
So there is all the stuff you might know from former versions of MVC. Formatter mappings, input formatters, output formatters, model binders, global filters and so on.
And you can, for instance, use here the output formatters collection to just register this ugly named class here. So in this case, you need the lamp. Where is the lamp? Is it called lamp?
Okay, for some reason auto import isn't supported here. You just need some additional, no, you just need the output formatter. When you do it right, everything works. Awesome.
Okay. Saying that, there is also a more convenient feature to set up the XML support. There is a convenience method that is just called at XML stuff, at XML serializer format.
things that is doing the same or I think the action name is at XML data contract serializer for matters, which is doing exactly what I've showed before. Okay, we are running out of time here, but that isn't a problem because I'm nearly at the end of this talk.
Let me quickly sum up all those things. We've seen that asp.net core one is across platform solution that runs on Windows, but also on Mac on Linux. We've seen or we've heard that we have this F5 compile to memory experience. We have side by side deployment
possibilities. That means we can deploy the parts of the dot net framework we need alongside of our application. So we don't need to make friends with the administrator
anymore. We have self hosting. So we have a very lightweight solution to run our asp.net application within a self first di di everywhere. Di is baked into asp.net core, and we have these new features of tech helpers. In addition of that, we have a unification of MVC and
Web API, awesome thing. Both is now one and solely one framework, namely MVC core one. The high level APIs are quite the same, but we have to align with MVC style routing.
The Web API style routing has gone. The low level APIs, like the APIs for the configuration or the APIs for locking or for session handling, they have been changed dramatically because we needed to get rid of system back. And in addition to that, you don't need
to hurry because the current versions are still maintained. Of course, further development will mainly take happen within the core branch, but the old versions, the current versions will still be maintained. So you need to hurry to migrate to the new asp.net core
world. So and that's it. Thank you for coming and have a nice day.