Overloading action methods that use identical HTTP verbs is tricky in ASP.NET Core 5, but there are a number of ways to do it. Let’s explore them.
ASP.NET Core 5 is an open source web application development framework for building modern web applications. Because ASP.NET Core 5 is built on the .NET Core runtime, you can take advantage of it to build and run applications on Windows, Linux, and the Mac. It should be noted that ASP.NET Core 5 combines the features of Web API as well as MVC. You can download .NET 5.0 here.
Method overloading, or the ability to have multiple methods share a name while differing in signature, is commonly used in C# but it is not especially straightforward in ASP.NET 5. This article talks about how you can overload action methods in ASP.NET 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.
Create an ASP.NET Core MVC 5 project in Visual Studio 2019
First off, let’s create an ASP.NET 5 project in Visual Studio 2019. Following these steps should create a new ASP.NET 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.
We’ll use this project in the sections below to illustrate how we can overload action methods in ASP.NET 5.
What is an action method?
Action methods are the public methods of a controller class that are not decorated by a [NonAction] attribute. Although they are similar to normal methods, they have to abide by the constraints given below:
- Action methods must be public
- Action methods cannot be static
- Action methods cannot be overloaded based on parameters similar to method overloading
The default action method that is created when you create a new MVC project is Index. The name of the default action method 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?}");
});
You can change the default action name by specifying a different name as shown in the code snippet given below.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Values}/{id?}");
});
Overload action methods using the same verb
At first glance the HomeController class would look like this:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None,
NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ??
HttpContext.TraceIdentifier });
}
}
The compiler will not flag any error because it will treat the new version of the Index method as an overload of the Index method that doesn’t accept any parameters. However, when you execute the application, you’ll be presented with a runtime error shown in Figure 1 below.
Overload action methods using a different verb
Let’s now change the HTTP verb of the newly created overload of the Index method as shown below.
[HttpPost]
public IActionResult Index(string text)
{
return View();
}
When you execute the application now, you will not see any compilation or runtime errors but will be presented with the welcome screen shown in Figure 2.
Overload action methods using the [ActionName] attribute
You can take advantage of the ActionName attribute to overload action methods. In this case, the action names must be different, as shown in the code snippet given below.
[ActionName("Index")]
public IActionResult Index()
{
return View();
}
[ActionName("Index With Parameter")]
public IActionResult Index(string text)
{
return View();
}
When you execute this code, there will not be any compile time or run time errors and you will be presented with the welcome screen as shown in Figure 2 above.
Overload action methods by using attribute routing
You can also overload action methods by configuring attribute routing. The following code snippet illustrates how this can be achieved.
public IActionResult Index()
{
return View();
}
[Route("Home/Index/{i:int}")]
public IActionResult Index(int i)
{
return View();
}
[Route("Home/Index/{isDeleted:bool}")]
public IActionResult Index(bool isDeleted)
{
return View();
}
Overload action methods using the [NonAction] attribute
You can take advantage of the [NonAction] attribute make sure that a particular method is not treated as an action method by the runtime. The following code snippet illustrates how the Index action method can be overloaded in this way.
public IActionResult Index()
{
return View();
}
[NonAction]
public IActionResult Index(string text)
{
return View();
}
In ASP.NET 5, if you give two action methods the same name, it results in an ambiguity — the runtime has to decide on which action method to call. (Note that the search for a matching action name is case-sensitive.) Disambiguating an URL into multiple overloaded action methods is tricky. But as we’ve discussed in this article, there are several ways to do this.
How to do more in ASP.NET Core:
- 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