C# 用于在初始化时创建对象的API控制器
我目前有一个名为“People”的API控制器,它继承了ApiController 控制器中有多个C# 用于在初始化时创建对象的API控制器,c#,api,C#,Api,我目前有一个名为“People”的API控制器,它继承了ApiController 控制器中有多个[HttpPost]/[HttpGet]方法。每个都使用相同的启动。即: [HttpPost] [Route(@"{personID}"] public async SavePerson(int personID, [FromBody] PersonObject sentPerson) { // Here is the initialization method that goes and
[HttpPost]
/[HttpGet]
方法。每个都使用相同的启动。即:
[HttpPost]
[Route(@"{personID}"]
public async SavePerson(int personID, [FromBody] PersonObject sentPerson) {
// Here is the initialization method that goes and gets a person
// dependent on if they have a record already
var getPerson = _personRepo.GetPerson(personID);
// some code here
}
每个方法在存储库中使用相同的getPerson
方法。但是,在MVC控制器中
可以调用多个覆盖
,例如OnActionExecuting
等
在初始化APIController
时,是否有一种方法可以运行:
var getPerson = _personRepo.GetPerson(personID);
在运行“People”类中的任何方法之前?这意味着我不必为每个新的
路线重复重写上述方法
您可以为类创建Person
属性和设置该属性的ActionFilter
:
ActionFilter:
public class MyActionFilter : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
//Add other criterias and required null checkings here
//Find the person id from action arguments
int personID = Convert.ToInt32(actionContext.ActionArguments["personID"]);
var _personRepo = new PersonRepository();
//Get the controller instance that is running and set the Person property
((People)actionContext.ControllerContext.Controller).Person = _personRepo.GetPerson(personID);
}
}
[MyActionFilter]
public class ValuesController : ApiController
{
public Person Person { get; set; }
//your actions
}
控制器:
public class MyActionFilter : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
//Add other criterias and required null checkings here
//Find the person id from action arguments
int personID = Convert.ToInt32(actionContext.ActionArguments["personID"]);
var _personRepo = new PersonRepository();
//Get the controller instance that is running and set the Person property
((People)actionContext.ControllerContext.Controller).Person = _personRepo.GetPerson(personID);
}
}
[MyActionFilter]
public class ValuesController : ApiController
{
public Person Person { get; set; }
//your actions
}
然后用[MyActionFilter]
然后,在任何用
[MyActionFilter]
修饰的操作中,您可以使用this.Person
您应该看看ActionFilter如何使用控制器的构造函数?