• No results found

107MVC Controllers and action methods

Creating web pages with MVC Controllers

107MVC Controllers and action methods

VIEWRESULTAND REDIRECTRESULT

When you’re building a traditional web application and generating HTML, most of the time you’ll use the ViewResult, which generates an HTML response using Razor (by default). We’ll look in detail as to how this happens in chapter seven.

You’ll also commonly use the various redirect-based results to send the user to a new web page. For example, when you place an order on an ecommerce website you typically navigate through multiple pages, as shown in figure 4.13.

Browser ASP.NET Core Application

Checkout

Buy

Payment

Submit

Order Complete!

The user clicks the buy button on thecheckout page

which sends a POST to the web application POST to /checkout 302 REDIRECT to /payment GET to /payment 200 OK (HTML) POST to /payment 302 REDIRECT to /order-complete GET to /order-complete 200 OK (HTML)

The ASP.NET Core application begins the checkout process

and sends a 302 redirect response to the payment page

The user's browser automatically follows the redirect to the payment page

The request for the payment page is handled by the app, generating an HTML page and returning it

to the browser The user fills in the the payment

form andclicks the submit button which sends a POST to the web application

The ASP.NET Core application processes the payment and sends a 302 redirect response

to the order complete page The user's browser

automatically follows the redirect to the order complete

page

The request for the order complete page is handled by generating an HTML page and returning it

to the browser

The user views the HTML order complete page

GET to /checkout

200 OK (HTML)

The user begins by navigating to the checkout page, which sends a GET request to the ASP.NET Core application

The request for the checkout page is handled by the app, generating an HTML page and returning it

to the browser

£

Figure 4.13 A typical POST, REDIRECT, GET flow through a website. A user sends their shopping basket to a checkout page which validates its contents and redirects to a payment page without the user having to manually change the URL.

tion sends HTTP redirects whenever it needs you to move to a different page, such as when a user submits a form. Your browser automatically follows the redirect requests giving a seamless flow through the checkout process.

NOTFOUNDRESULTAND STATUSCODERESULT

As well as HTML and redirect responses, you’ll occasionally need to send specific HTTP status codes. For example, if you request a page for viewing a product on an ecommerce application, and that product doesn’t exist, a 404 HTTP status code is returned to the browser and you’ll typically see a “Not found” web page. The MvcMid- dleware can achieve this behavior by returning a NotFoundResult, which returns a raw 404 HTTP status code. You could achieve a similar result using the StatusCodeRe- sult and setting the status code returned explicitly to 404.

Note that the NotFoundResult doesn’t generate any HTML; it only generates a raw 404 status code and returns it back through the middleware pipeline. But, as dis- cussed in the previous chapter, you can use the StatusCodePagesMiddleware to inter- cept this raw 404 status code after it’s been generated, and provide a user friendly HTML response for it.

CREATING ACTIONRESULTSUSINGHELPERMETHODS

ActionResults can be created and returned using the normal new syntax of C#

return new ViewResult()

but if your controller inherits from the base Controller class, then you can also use one of the helper methods for generating an appropriate response. It’s common to use the View method to generate an appropriate ViewResult, the Redirect method to generate a RedirectResponse, or the NotFound method to generate a NotFound- Result.

TIP Most ActionResults have a helper method on the base Controller class. They’re typically named Type where the result generated’s called TypeResult. For example, the Content method returns a ContentResult instance.

As discussed, the act of returning an IActionResult doesn’t immediately generate the response—it’s the execution of an IActionResult by the MvcMiddleware, which occurs outside the action method. After producing the response, the MvcMiddleware returns it back to the middleware pipeline. From there, it passes through the registered mid- dleware in the pipeline, before the ASP.NET Core web serve finally sends it to the user. By now you should have an overall understanding of the MVC design pattern and how it relates to ASP.NET Core. The action methods on a controller are invoked in response to given requests and are used to select the type of response to generate by returning an IActionResult.

In traditional web apps, the MvcMiddleware generates HTML web pages. These can be served to a user who is browsing your app with a web browser, as you’d see with a traditional website. It’s also possible to use the MvcMiddleware to send data in a

109 Summary

ods, as you’ll see in chapter nine. Controllers handle these use cases, the only tangible difference being the data they return. These are typically known as MVC and Web API controllers respectively.

It’s important to remember that the whole MVC infrastructure in ASP.NET Core’s a piece of middleware that runs as part of the middleware pipeline, as you saw in the previous chapter. Any response generated, whether a ViewResult or a RedirectRe- sult, will pass back through the middleware pipeline, giving a potential opportunity for middleware to modify the response before the web server sends it to the user.

An aspect I’ve only vaguely touched on is how the MvcMiddleware decides which action method to invoke for a given request. This process is handled by the routing infrastructure, and is a key part of MVC in ASP.NET Core. In the next chapter, you’ll see how to define routes, how to add constraints to your routes, and how they decon- struct URLs to match a single action and controller.

4.3

Summary

In this chapter, you learned that

 MVC allows for a separation of concerns between the business logic of your application, the data passed around, and the display of data in a response.  Controllers contain a logical grouping of action methods.

 ASP.NET Core Controllers inherit from the Controller base class, or have a name that ends in “Controller”.

 Action methods decide what sort of response to generate; action results handle the actual generation.

 Action methods should generally delegate to services to handle the business logic required by a request, instead of performing the changes themselves. This ensures a clean separation of concerns that aids testing and improves applica- tion structure.

 Action methods can have parameters whose values are taken from properties of the incoming request.

 When building a traditional web application, you’ll generally use a ViewResult to generate an HTML response.

 You can send users to a new URL using a RedirectResult.

 The Controller base class exposes many helper methods for creating an ActionResult.

 The MVC and Web API infrastructure’s unified in ASP.NET Core. The only thing that differentiates a traditional MVC controller from a Web API control- ler’s the data it returns. MVC controllers normally return a ViewResult, whereas Web API controllers typically return data or a StatusCodeResult.

ASP.NET Core is a re-imagining of the .NET Framework that frees developers from Visual Studio and Windows. You can now build and run cross-platform .NET applica- tions on any OS, with any IDE, and using the tools that you choose. The entire framework is open-source, and has been developed with many contributions from the community. While ASP.NET Core is relatively new, Micro- soft is heavily investing in it, promoting ASP.NET Core as their web framework of choice for the foreseeable future. Whether you are building traditional web applications or highly performant APIs for client side or mobile applica- tions, ASP.NET Core could be the framework for you. ASP.NET Core in Action is for C# developers without any web development experi- ence who want to get started and productive using ASP.NET Core to build web appli- cations. In the first half of the book, you will work through the basics of a typical ASP.NET Core application, focusing on how to create basic web pages and APIs using MVC controllers and the Razor templating engine. In the second half, you will build on this core knowledge looking at more advanced requirements and how to add extra features to your application. You will learn how to secure your application behind a login screen, how to handle configuration and dependency injection, and how to deploy your application to production. In the last part of the book you will look in depth at further bending the framework to your will by creating custom components and using more advanced features of the framework.

What's inside:

 Using MVC to deliver dynamically generated web pages  Securing applications with login requirements

 Interacting with a RDMS using Entity Framework Core  Publishing an ASP.NET Core application to a server  Unit and integration testing

 Creating custom middleware and filters

M

any applications access relational databases. This chapter from Jon P. Smith’s Entity Framework Core in Action introduces how to use the completely rewritten Entity Framework Core for data access. Despite being rebuilt from the ground up, migrating from Entity Framework to Entity Framework Core is fairly straightforward. If you’re new to Entity Framework, Jon will introduce you to this powerful library and its many benefits.

Querying the