如何集中多个 Web API 控制器共享的代码?

How do I centralize code shared by multiple Web API controllers?

我目前有将近 10 个控制器共享相同的代码。代码很简单,就是检查一组数据是否为null,并检查当前用户是否有访问该数据的权限。

如果有问题,我会抛出一个 HttpResponseException。

代码在每个控制器中都有效。我也设法集中了代码,但我认为我这样做的方式是错误的。我创建了一个继承 ApiController 的新 class,然后我让控制器继承了我的新 class。这是让 HttpResponseExceptions 正常工作的唯一方法。代码如下:

//New centralized class:

public class AuthorizationClass : ApiController
{   
    private DataModel db = new DataModel();

    public async Task checkUserisValid(int user_id)
    {
        user_list user_list = await db.user_list.FindAsync(user_id);

        if (user_list == null)
        {
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,"This user does not exist"));
        }

        int businessID = user_list.business_id;

        var result = checkAccess(User.Identity.Name, businessID);

        if (result.Count <= 0)
        {
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to modify this business"));
        }
    }

    public static List<user_details> checkAccess(string userName, int id)
    {
        //code which checks if the user is in the right tables
            return checkAccess.ToList();
    }
}

然后在控制器class中,我有:

    public class MyController : AuthorizationClass 
{
        public async Task<IHttpActionResult> Postnew_table(int id, new_table new_table)
        {
            await checkUserisValid(id);

        //rest of controller    
            }
}   

我尝试以不同的方式来实现它,但这是我可以让它与 HttpResponseException 一起工作的唯一方式。有没有更好的方法可以在不继承 classes 的情况下做到这一点,或者这是实现我所追求的唯一方法吗?

谢谢。

您可以将这 2 个方法移动到公共程序集中的某个静态助手 class,您提到 Request 是控制器上的一个实例变量,只需将其传递给该方法即可。

public static class SomeHelper
{
    public static async Task checkUserisValid(int user_id, DataModel db, Request request, User user)
    {
       user_list user_list = await db.user_list.FindAsync(user_id);

       if (user_list == null)
       {
          throw new   HttpResponseException(request.CreateErrorResponse(HttpStatusCode.BadRequest,"This user does not exist"));
        }

        int businessID = user_list.business_id;

        var result = checkAccess(user.Identity.Name, businessID);

        if (result.Count <= 0)
        {
          throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to modify this business"));
        }
   }

  public static List<user_details> checkAccess(string userName, int id)
  {
      //code which checks if the user is in the right tables
          return checkAccess.ToList();
   }

}