ASP.NET Core 2 and Angular 5
上QQ阅读APP看书,第一时间看更新

Controllers/SampleDataController.cs

The HomeController is a perfect example of a standard MVC Controller returning Views; conversely, the SampleDataController.cs is only returning structured JSON data, thus making it conceptually closer to the APIControllers featured by the ASP.NET Web API framework. Luckily enough, the new MVC 6 merged the best of both worlds into one, which means that there's no difference between these two kinds of controllers anymore; we're free to return any content we want from within the same controller class.

That said, there's no need to dig much into this controller's code for now; we'll do that soon enough, starting from Chapter 2, Backend with .NET Core. Let's just take a look at the resulting JSON data by issuing a couple of requests.

Start the application in debug mode by clicking on the Run button or pressing the F5 keyboard key; then, replace the /home part of the address bar URL with /api/SampleData/WeatherForecasts. The full URL should be just like the following:

http://localhost:<port>/api/SampleData/WeatherForecasts

We should be able to see something like this:

These are the raw (sample) data elements coming out from the server. Now, point the URL back to /home, which will bring us back to the Home View. From there, click on the Fetch data link from the left menu to get the following:

These are the same data elements mentioned earlier, fetched and served by Angular through the sample SPA provided by our current project template. All the GUI elements--menu links, page title, and labels, HTML code, CSS styles, and so on--are inside the /ClientApp/ folder; the server-side code only provides the raw data, just like it's meant to be.