简体   繁体   中英

How to call a function written in one controller from another controller in mvc

I have 2 controllers called LoginController and RegisterController and a function 'public static string Encrypt(string toEncrypt, bool useHashing)' is defined in RegisterController.How can I call the same from LoginController?

I used var result= new RegisterController().Encrypt(newpass, true); code but results : Error 4 Member 'AP.WebApp.Controllers.RegisterController.Encrypt(string, bool)' cannot be accessed with an instance reference; qualify it with a type name instead

You can solve this with inheritence.

Example:

public abstract class BaseController : Controller 
{ 
    //Common functionality between controllers go here
    protected static string Encrypt(string toEncrypt, bool useHashing)
    {
        //Your content
    } 
}

public class LoginController : BaseController //not Controller anymore 
{
    //Encrypt is now available

    //...Your controller methods here
}

public class RegisterController : BaseController //not Controller anymore 
{
    //Encrypt is now available

    //...Your controller methods here
}

As others have said, it's not good design to share a static method from one controller to another.

I suggest you create a new class, for example Common, that contains the definition of your shared function. It could look like:

public class MyCommonUtilities
{
    public static string Encrypt(string ToEncrypt, bool useHashing)
    {
        // insert code here
    }
}

If you define this in a separate common project, then be sure to include this class in both of your controllers (note: not required if you define this class in the same namespace as the controllers)

using MyCommonUtilities;

and call it where you need it in each controller. This centralizes the method into a common section of code and makes it available consistently to any controller.

Your method is static on the register controller, so you shold just call:

RegisterController.Encrypt(newpass,true);

Or remove the static key word from the method.

I recommend to create a Encrypt class, which has Encrypt static class. Then you can call it from whatever you want.

This is not good way to call one method from another controller. for that create common public class which can be access by anywhere from project. One simple solution is create a method with JsonResult in RegisterController add your functionality and calculation in method. Call this method by http WebRequest.

我有一个方法,创建一个继承自Controller的基本控制器,然后这两个控制器将由新创建的基本控制器继承,它具有公共代码(加密),以便您可以在两个控制器中调用方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM