Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - Update base controller variable values but all derived controllers are not updated in ASP.NET Core

This is my BaseController:

public abstract class BaseController : Controller
{
    public Int64 CompanyId { get; set; } // I need to update this property
}

I have another 2 controllers, CompanyController:

public class CompanyController : BaseController
{
   
    public IActionResult ChangeCompany(long CompanyId = 35)  //
    {   
        base.CompanyId = CompanyId;
        // other code
    }

    public IActionResult GetCompany()  //
    {   
        return base.CompanyId  // return 35
    }
}

and AccountController:

public class AccountController : BaseController
{
    public IActionResult GetCompany()  //
    {   
        return base.CompanyId  // return 0
    }
}

How can I get the updated CompanyId value from AccountController?

question from:https://stackoverflow.com/questions/65857005/update-base-controller-variable-values-but-all-derived-controllers-are-not-updat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't. Each object is different and the base class is just a template that your other classes extend. Every new object will create and maintain their own CompanyId variable, so you can't and shouldn't change the one by changing the other.

Check the static keyword if you want one value only for all the classes public static Int64 CompanyId { get; set; }

Basically this:

public class CompanyController : BaseController
{
   
    public IActionResult ChangeCompany(long CompanyId = 35)  //
    {   
        base.CompanyId = CompanyId;
        // other code
    }

    public IActionResult GetCompany()  //
    {   
        return base.CompanyId  // return 35
    }

}

Is the same as this (though without inheritance, you can't even know which parts the two classes have in common):

public class CompanyController
{
    public Int64 CompanyId { get; set; } // I need to update this property
    public IActionResult ChangeCompany(long CompanyId = 35)  //
    {   
        base.CompanyId = CompanyId;
        // other code
    }

    public IActionResult GetCompany()  //
    {   
        return base.CompanyId  // return 35
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...