控制器中所有方法的通用代码 class
common code for all methods in a controller class
我有 10 个控制器使用相同的代码块,但我不知道如何一次编写代码并在所有地方使用它。
我必须定义一个名为的对象:
requiredStructuralSupportParameters
,然后在对象中设置3个字段。
这是使用它的控制器方法之一:
public class StructureController : Controller
{
public IActionResult Index()
{
var requiredStructuralSupportParameters = new Structure.RequiredInfo()
{
Steel = "1500y",
Concrete = "5500l",
Rebar = "95000y"
};
var response = callToAPI(requiredStructuralSupportParameters);
return response.Results;
}
}
我曾尝试取出该代码并将其放在控制器 class 的顶部并使其成为 public,但是我的控制器无法看到它并且出现 nullreferenceexception 错误。
所以只有当我将它直接放在控制器方法中时它才有效。
有没有办法让所有控制器都可以重复使用相同的代码块?
public class StructureController : Controller
{
protected YourType _requiredStructuralSupportParameters;
public StructureController()
{
this._requiredStructuralSupportParameters = new Structure.RequiredInfo()
{
Steel = "1500y",
Concrete = "5500l",
Rebar = "95000y"
};
}
}
然后让你的其他控制器继承你的 StructureController
:
public SomeController : StructureController{
public IActionResult Index() {
var response = callToAPI(this._requiredStructuralSupportParameters);
return response.Results;
}
}
还没有测试过,但我希望你有一个想法
我有 10 个控制器使用相同的代码块,但我不知道如何一次编写代码并在所有地方使用它。
我必须定义一个名为的对象:
requiredStructuralSupportParameters
,然后在对象中设置3个字段。
这是使用它的控制器方法之一:
public class StructureController : Controller
{
public IActionResult Index()
{
var requiredStructuralSupportParameters = new Structure.RequiredInfo()
{
Steel = "1500y",
Concrete = "5500l",
Rebar = "95000y"
};
var response = callToAPI(requiredStructuralSupportParameters);
return response.Results;
}
}
我曾尝试取出该代码并将其放在控制器 class 的顶部并使其成为 public,但是我的控制器无法看到它并且出现 nullreferenceexception 错误。
所以只有当我将它直接放在控制器方法中时它才有效。
有没有办法让所有控制器都可以重复使用相同的代码块?
public class StructureController : Controller
{
protected YourType _requiredStructuralSupportParameters;
public StructureController()
{
this._requiredStructuralSupportParameters = new Structure.RequiredInfo()
{
Steel = "1500y",
Concrete = "5500l",
Rebar = "95000y"
};
}
}
然后让你的其他控制器继承你的 StructureController
:
public SomeController : StructureController{
public IActionResult Index() {
var response = callToAPI(this._requiredStructuralSupportParameters);
return response.Results;
}
}
还没有测试过,但我希望你有一个想法