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

时间:2015-01-02 00:32:09

标签: asp.net asp.net-web-api asp.net-web-api2 code-reuse

我有近10个控制器,它们目前共享相同的代码。代码非常简单,只是检查一组数据是否为空,并检查当前用户是否有权访问数据。

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

代码在每个控制器中都有效。我也设法集中代码,但我认为我做的方式是错误的。我创建了一个继承ApiController的新类,然后让控制器继承我的新类。这是我可以使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();
    }
}

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

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

        //rest of controller    
            }
}   

我尝试以不同的方式做到这一点,但这是我可以使用HttpResponseException的唯一方法。有没有更好的方法来做这个而不继承类,或者这是我做的事情的唯一方法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

你可以将这两个方法移动到一个公共程序集中的某个静态帮助器类,你提到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();
   }

}
相关问题