How to overload action method in asp.net core 5

Time:2021-9-1

Asp.net core 5 is an open source development framework for building modern web programs. Because asp.net core 5 is based on the. Net core runtime, with it, you can run web programs on windows, Linux and MAC. It is worth noting that asp.net core 5 integrates web API and MVC.

Now back to this topic, what is method overloading? It is a technology that allows multiple methods with different signatures to share a method name. This technology is widely used in c# but it is not so intuitive in asp.net 5. In this article, we will discuss how to overload action.

What is action

Action is marked as public under the controller and is not[NonAction] The method of property marking is as follows:


    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

Although it looks like a normal method, these methods must comply with the following constraints.

  • Action method must be public
  • Action cannot be static
  • Action methods cannot be overloaded with parameters like ordinary methods

When you create an MVC project, the default index action will also be created automatically. This action is also configured by default in the routing configuration under startup. Configure, as shown in the following code:


    public class Startup
    {
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

If you don’t want to use the default index, you can change it to something else you think is appropriate, such asValues


    public class Startup
    {
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Values}/{id?}");
            });
        }
    }

Overload the action method with the same predicate verb

First, take a look at what the homecontroller class looks like.


    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Index(string text)
        {
            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
            });
        }
    }

Note that I added a new one in the above classpublic IActionResult Index(string text)Method, the compiler does not give any error prompt. However, when you run the application, you will encounter a runtime error, as shown in the following figure:

How to overload action method in asp.net core 5

Overloading action with different predicate verbs

Now modify the overloaded method index to mark the newly added overloaded methodHttpPostThe characteristic code is as follows:


[HttpPost]
public IActionResult Index(string text)
{
   return View();
}

When the application is run again, there will be no compile time or run-time errors this time, as shown in the following figure:

How to overload action method in asp.net core 5

Overload action with actionname attribute

You can overload the action method through the actionname attribute. It is worth noting that the tag names in the actionname attribute cannot be the same, as shown in the following code:


[ActionName("Index")]
public IActionResult Index()
{
    return View();
}
[ActionName("Index With Parameter")]
public IActionResult Index(string text)
{
     return View();
}

Run the program again. Everything is OK without any compile time or run-time errors. The screenshot is as follows:

How to overload action method in asp.net core 5

Overload action with route attribute

You can use the routeattribute feature to implement action overloading. The following code fragment shows how to implement it.


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 with nonaction attribute

You can use nonactionattribute to mark some methods, so that asp.net core will not treat this method as an action at runtime. The following code shows the overload of index using nonactionattribute on index.


public IActionResult Index()
{
    return View();
}

[NonAction]
public IActionResult Index(string text)
{
    return View();
}

In asp.net 5, if the names of two actions are the same, it will be very embarrassing for the runtime. Because it takes action as the unit, it will return runtime errors. Another thing to note is that the names of actions are case insensitive, that is:/Home/Indexand/HOME/INDEXIt is the same, so it is a very skilled technology to cut into each overload method through the change of URL. The solution is to perfectly realize it through several methods introduced in this article!

Translation link: https://www.infoworld.com/art…

More high quality dry goods: see my GitHub: csharpranslate

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]