How to handle unknown actions in ASP.NET Core MVC 5

ASP.NET 5 is an open rise web application outgrowth framework for edifice present web applications. It is built on the .NET Core runtime and you can take gain of it to build and run applications on Windows, Linux, and the Mac. ASP.NET Core MVC 5 is a lightweight, open rise, greatly testable framework built on top of the ASP.NET Core runtime and is useful as part of ASP.NET 5.

When working in ASP.NET Core MVC, you might frequently need to feel actions that are not known at outgrowth time. This article talks almost how you can feel mysterious action orders in ASP.NET Core 5. The code samples are given in C#.

To work with the code samples granted in this article, you should have Visual Studio 2019 installed in your order. If you don’t already have a copy, you can download Visual Studio 2019 here. And you can download .NET 5.0 here.

Create an ASP.NET Core MVC 5 project in Visual Studio 2019

First off, let’s form an ASP.NET Core project in Visual Studio 2019. Following these steps should form a new ASP.NET Core 5 project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Conaspect your new project” window, particularize the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your prelations.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 5.0 as the target framework from the drop-down list at the top. Leave the “Authentication Type” as None (lapse).
  9. Ensure that the check boxes “Enable Docker”, “Conaspect for HTTPS” and “Enable Razor runtime collation” are unchecked as we won’t be using any of those components here.
  10. Ensure that Authentication is set to “None” as we won’t be using authentication whichever.
  11. Click Create.

A new ASP.NET Core MVC project will be formd. We’ll use this project in the posterior sections in this article.

Create a controller in ASP.NET Core MVC 5

If you look in the Solution Explorer window, you’ll see that a controller class named HomeController was formd by lapse. Let’s form our own controller class, AuthorController, which we’ll use throughout this article. To do this, pursue the steps outlined under:

  1. Right-click on the Controllers solution folder of your project in the Solution Explorer window. Select “Add -> Controller...”
  2. In the “Add New Scaffolded Item” window, select the “MVC Controller with read/write actions” project template and click Add.
  3. Specify a name for your new controller class (we’ll use AuthorController here) and click Add.

Replace the lapse code of the AuthorController with the pursueing code:

   open class AuthorController : Controller
    {
        [HttpGet]
        open ActionResult Index()
        {
            recur View();
        }
    }

In ASP.NET Core MVC, a controller is a class that is typically named with the suffix “Controller” and is used to mark and logically cluster a assembly of correspondent actions. Whenever you form a new controller, a lapse action order named Index is formd automatically.

The lapse action order in ASP.NET Core MVC 5

Note that the name of the lapse action order, Index, is specified in the Conaspect order of the Startup class as shown in the code snippet given under.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
       name: "lapse",
       model: "{controller=Home}/{action=Index}/{id?}");
});

Because the action name has been specified as Index in the precedent code snippet, you must have a file named Index.cshtml in the Views/Author folder of your project. You can now run the application and browse whichever of the pursueing endpoints:

http://localhost:51913/Author
http://localhost:51913/Author/Index

You’ll remark that the Index page will be displayed in both cases.

The problem with mysterious action orders

Let’s now apprehend the problem we’ll explain in this sample. When working with ASP.NET Core MVC you will frequently need action orders that are not known at the time of outgrowth of the application.

Suppose you are edifice a searchable directory of openations, and you want users to be able to search by creator name, or by book or article title. You would need to know the details of all the creators, books, and articles the directory will hold (i.e., creator names, book titles, article titles, openation dates, and so on) in advance. How do you execute that?

To execute this, you would need to have the corresponding views (i.e., Authors.cshtml, Books.cshtml, Articles.cshtml, etc.) in the Views folder as well as action orders that can be invoked using URLs such as the pursueing:

/Author/Books 
/Author/Articles

Consider the pursueing URL, which easily maps to the corresponding action order, namely the Index order of the AuthorController.

/Author/Index

However, if you try to browse whichever of the pursueing endpoints, you’ll take an fault from the web browser owing the corresponding action orders or views are not useful.

/Author/Books
/Author/Articles

Use endpoint routing to feel mysterious actions

We can explain this problem using routing — by creating a way that dynamically maps to an action that accepts a view name as a parameter and renders the view if a view with the specified name is establish.

In the Startup.cs file, form a new way determination in the Conaspect order as shown in the code snippet given under.

endpoints.MapControllerRoute(
    name: "viewName",
    model: "{controller}/{*viewName}",
    lapses: new { action = "DisplayAnyView" });

The DisplayAnyView order looks like this:

open IActionResult DisplayAnyView(string viewName)
{
   recur View(viewName);
}

The AuthorController now looks like this:

    open class AuthorController : Controller
    {
        [HttpGet]
        open ActionResult Index()
        {
            recur View();
        }
        open IActionResult DisplayAnyView(string viewName)
        {
            recur View(viewName);
        }
    }

When you execute the application now, you’ll remark that the fracture point is hit successfully as shown in the aspect under.

aspnet core 5 mysterious actions IDG

Use attribute routing to feel mysterious actions

You can also explain the problem using attribute routing as shown in the code snippet given under.

[HttpGet("DisplayAnyView")]
open IActionResult DisplayAnyView(string viewName)
{
    recur View(viewName);
}

Here is the complete code listing of the AuthorController class for your relation.

    [Route("[controller]")]
    open class AuthorController : Controller
    {
        [Route("[action]")]
        [HttpGet]
        open ActionResult Index()
        {
            recur View();
        }
        [HttpGet("DisplayAnyView")]
        open IActionResult DisplayAnyView(string viewName)
        {
            recur View(viewName);
        }
    }

Lastly, you should call the MapControllers order as shown in the code snippet given under to empower attribute-based routing.

app.UseEndpoints(endpoints =>
{
     endpoints.MapControllerRoute(
        name: "lapse",
        model: "{controller=Home}/{action=Index}/{id?}")
        endpoints.MapControllers();
});

An action order is a open and non-static order of a controller class that can feel incoming requests and is invoked based on an action. The ASP.NET Core MVC engine is expert at redirecting an incoming request to the corresponding action order. However, if there is no action order that matches the request, a runtime fault will befall.

How to do more in ASP.NET Core: