joydip_kanjilal
Contributor

How to overload action methods in ASP.NET Core MVC 5

how-to
Dec 07, 20207 mins
C#Microsoft .NETSoftware Development

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.

icons working out weight lifting
Credit: Thinkstock

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.

  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 “Configure your new project” window, specify 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 preferences.
  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 (default).
  9. 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.
  10. Ensure that Authentication is set to “None” as we won’t be using authentication either.
  11. 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:

  1. Action methods must be public
  2. Action methods cannot be static
  3. 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 figure 01 IDG

Figure 1.

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 figure 02 IDG

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:

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author