Getting ready

We can route HTTP requests to the correct Controllers by looking at what routing information is contained in the middleware of our application. The middleware then uses this routing information to see if the HTTP request needs to get sent to a Controller or not. Middleware will have a look at the incoming URL and match that up with the configuration information we provide it with. We can define this routing information in the Startup class using one of two routing approaches, namely:

  • Convention-based routing
  • Attribute-based routing

This recipe will explore these routing approaches. Before we can do that, we need to add the ASP.NET MVC NuGet package to our application. You should be rather familiar with adding NuGet packages to your application by now. Inside the NuGet Package Manager, browse for and install the Microsoft.AspNetCore.Mvc NuGet package. This will expose new middleware for our application, one of which is app.UseMvc();. This is used to map an HTTP request to a method in one of our Controllers. Modify the code in your Configure() method as follows:

loggerFactory.AddConsole();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Add("friendlyError.html");
app.UseDefaultFiles(options);

app.UseExceptionHandler("/friendlyError");
}

app.UseStaticFiles();
app.UseMvc();

Next, we need to register our MVC services that the MVC framework requires in order to function. Inside ConfigureServices() add the following:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

After this is complete, we have the basics set up for MVC to function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.196.172