C# 用于在初始化时创建对象的API控制器

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

我目前有一个名为“People”的API控制器,它继承了ApiController

控制器中有多个
[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如何使用控制器的构造函数?