In asp net core minimal api how can I have a common function where I can supply

In ASP.NET Core Minimal API, you can have a common function by a separate class or a method that can be accessed from different parts of your application. This allows you to reuse code and maintain a centralized logic for common functionalities.

To demonstrate this, let's consider an example you need to calculate the sum of two numbers in multiple places within your ASP.NET Core Minimal API application.

First, create a new class “Calculator” that contains a static method called “AddNumbers” which takes two integers as input and returns their sum. Here's how the code would look like:


public class Calculator
{
    public static int AddNumbers(int num1, int num2)
    {
         num1 + num2;
    }
}

Now, you can use this common function in different parts of your ASP.NET Core Minimal API application. For example, let's say you have a where you need to calculate the sum of two numbers and return the result as a response. Here's how you can do it:


using .AspNetCore.Mvc;

[]
[("api/[controller]")]
public class SumController : ControllerBase
{
    [HttpGet]
    public IActionResult GetSum(int num1, int num2)
    {
        int sum = Calculator.AddNumbers(num1, num2);
        return Ok(sum);
    }
}

In the above example, we have created a controller called “SumController” with a GET endpoint that accepts two integers as query . Inside the endpoint, we call the “AddNumbers” method from the “Calculator” class to calculate the sum and return it as a response.

By using a common function like this, you can easily reuse the logic for calculating the sum of two numbers in other parts of your ASP.NET Core Minimal API application without duplicating code.

Conclusion

In ASP.NET Core Minimal API, having a common function is essential for code reusability and maintaining a centralized logic. By creating a separate class or a static method, you can easily define and access common functionalities from different parts of your application. This approach helps in reducing code duplication and improving the overall maintainability of your ASP.NET Core Minimal API application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents