Handle unknown actions elegantly in ASP.NET 5 by creating routes that dynamically map to the views in your application. Credit: CarlosCastilla / Getty Images ASP.NET 5 is an open source web application development framework for building modern web applications. It is built on the .NET Core runtime and you can take advantage of it to build and run applications on Windows, Linux, and the Mac. ASP.NET Core MVC 5 is a lightweight, open source, highly testable framework built on top of the ASP.NET Core runtime and is available as part of ASP.NET 5. When working in ASP.NET Core MVC, you might often need to handle actions that are not known at development time. This article talks about how you can handle unknown action methods in ASP.NET Core 5. The code examples are given in C#. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. 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 create an ASP.NET Core project in Visual Studio 2019. Following these steps should create a new ASP.NET Core 5 project in Visual Studio 2019. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. 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 (default). Ensure that the check boxes “Enable Docker”, “Configure for HTTPS” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here. Ensure that Authentication is set to “None” as we won’t be using authentication either. Click Create. A new ASP.NET Core MVC project will be created. We’ll use this project in the subsequent 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 created by default. Let’s create our own controller class, AuthorController, which we’ll use throughout this article. To do this, follow the steps outlined below: Right-click on the Controllers solution folder of your project in the Solution Explorer window. Select “Add -> Controller…” In the “Add New Scaffolded Item” window, select the “MVC Controller with read/write actions” project template and click Add. Specify a name for your new controller class (we’ll use AuthorController here) and click Add. Replace the default code of the AuthorController with the following code: public class AuthorController : Controller { [HttpGet] public ActionResult Index() { return View(); } } In ASP.NET Core MVC, a controller is a class that is typically named with the suffix “Controller” and is used to define and logically group a collection of similar actions. Whenever you create a new controller, a default action method called Index is created automatically. The default action method in ASP.NET Core MVC 5 Note that the name of the default action method, Index, is specified in the Configure method of the Startup class as shown in the code snippet given below. app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); Because the action name has been specified as Index in the preceding code snippet, you must have a file called Index.cshtml in the Views/Author folder of your project. You can now run the application and browse either of the following endpoints: https://localhost:51913/Author https://localhost:51913/Author/Index You’ll observe that the Index page will be displayed in both cases. The problem with unknown action methods Let’s now understand the problem we’ll solve in this example. When working with ASP.NET Core MVC you will often need action methods that are not known at the time of development of the application. Suppose you are building a searchable directory of publications, and you want users to be able to search by author name, or by book or article title. You would need to know the details of all the authors, books, and articles the directory will contain (i.e., author names, book titles, article titles, publication dates, and so on) in advance. How do you achieve that? To accomplish 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 methods that can be invoked using URLs such as the following: /Author/Books /Author/Articles Consider the following URL, which easily maps to the corresponding action method, namely the Index method of the AuthorController. /Author/Index However, if you try to browse either of the following endpoints, you’ll receive an error from the web browser because the corresponding action methods or views are not available. /Author/Books /Author/Articles Use endpoint routing to handle unknown actions We can solve this problem using routing — by creating a route 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 found. In the Startup.cs file, create a new route definition in the Configure method as shown in the code snippet given below. endpoints.MapControllerRoute( name: "viewName", pattern: "{controller}/{*viewName}", defaults: new { action = "DisplayAnyView" }); The DisplayAnyView method looks like this: public IActionResult DisplayAnyView(string viewName) { return View(viewName); } The AuthorController now looks like this: public class AuthorController : Controller { [HttpGet] public ActionResult Index() { return View(); } public IActionResult DisplayAnyView(string viewName) { return View(viewName); } } When you execute the application now, you’ll observe that the break point is hit successfully as shown in the figure below. IDG Use attribute routing to handle unknown actions You can also solve the problem using attribute routing as shown in the code snippet given below. [HttpGet("DisplayAnyView")] public IActionResult DisplayAnyView(string viewName) { return View(viewName); } Here is the complete code listing of the AuthorController class for your reference. [Route("[controller]")] public class AuthorController : Controller { [Route("[action]")] [HttpGet] public ActionResult Index() { return View(); } [HttpGet("DisplayAnyView")] public IActionResult DisplayAnyView(string viewName) { return View(viewName); } } Lastly, you should call the MapControllers method as shown in the code snippet given below to enable attribute-based routing. app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}") endpoints.MapControllers(); }); An action method is a public and non-static method of a controller class that can handle incoming requests and is invoked based on an action. The ASP.NET Core MVC engine is adept at redirecting an incoming request to the corresponding action method. However, if there is no action method that matches the request, a runtime error will occur. How to do more in ASP.NET Core: How to overload action methods in ASP.NET Core 5 MVC How to use multiple implementations of an interface in ASP.NET Core How to use IHttpClientFactory in ASP.NET Core How to use the ProblemDetails middleware in ASP.NET Core How to create route constraints in ASP.NET Core How to manage user secrets in ASP.NET Core How to build gRPC applications in ASP.NET Core How to redirect a request in ASP.NET Core How to use attribute routing in ASP.NET Core How to pass parameters to action methods in ASP.NET Core MVC How to use API Analyzers in ASP.NET Core How to use route data tokens in ASP.NET Core How to use API versioning in ASP.NET Core How to use Data Transfer Objects in ASP.NET Core 3.1 How to handle 404 errors in ASP.NET Core MVC How to use dependency injection in action filters in ASP.NET Core 3.1 How to use the options pattern in ASP.NET Core How to use endpoint routing in ASP.NET Core 3.0 MVC How to export data to Excel in ASP.NET Core 3.0 How to use LoggerMessage in ASP.NET Core 3.0 How to send emails in ASP.NET Core How to log data to SQL Server in ASP.NET Core How to schedule jobs using Quartz.NET in ASP.NET Core How to return data from ASP.NET Core Web API How to format response data in ASP.NET Core How to consume an ASP.NET Core Web API using RestSharp How to perform async operations using Dapper How to use feature flags in ASP.NET Core How to use the FromServices attribute in ASP.NET Core How to work with cookies in ASP.NET Core How to work with static files in ASP.NET Core How to use URL Rewriting Middleware in ASP.NET Core How to implement rate limiting in ASP.NET Core How to use Azure Application Insights in ASP.NET Core Using advanced NLog features in ASP.NET Core How to handle errors in ASP.NET Web API How to implement global exception handling in ASP.NET Core MVC How to handle null values in ASP.NET Core MVC Advanced versioning in ASP.NET Core Web API How to work with worker services in ASP.NET Core How to use the Data Protection API in ASP.NET Core How to use conditional middleware in ASP.NET Core How to work with session state in ASP.NET Core How to write efficient controllers in ASP.NET Core Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos