2013-08-01 34 views
0

是否可以向所有控制器添加强制参数? 我开发RESTful api,所以我想为每个路由都要求特殊的“apikey”参数。AttributeRouting强制性参数

 [HttpPut] 
    [PUT("create")] 
    public PostDto Create(string title, string description, string tag, long photo, float lat, float lon, int error) 
    { 
     if (description.Length > DescriptionMaxLength) 
      throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength)); 

     throw new NotImplementedException(); 
    } 

    [HttpPost] 
    [POST("edit/{id:int}")] 
    public bool Edit(int id, string title, string description, int? photo) 
    { 
     if (description.Length > DescriptionMaxLength) 
      throw new ApiException(ErrorList.TooLongDescription, string.Format("Description is more than {0}", DescriptionMaxLength)); 

     throw new NotImplementedException(); 
    } 

    [HttpDelete] 
    [DELETE("delete/{id:int}")] 
    public bool Delete(int id) 
    { 
     if (id < 0) 
      throw new ApiException(ErrorList.InvalidValue, "id is smaller than 0"); 

     throw new NotImplementedException(); 
    } 

但我不想为每种方法手动执行此操作。

+0

对于像'apikey'这样的必要参数,我将在验证方法中使用BaseController或ActionFilter进行验证。如果您稍后需要访问apikey,则始终可以假定它存在。如果需要,您也可以将过滤器将api键推入Context.Items集合中或类似的东西。 –

回答

1

首先,您需要确定您要在操作正文中检索API密钥的确切方式。 由于您不想将它作为方法的参数传递,因此它可以是控制器的属性(不是最好的方法,您必须创建一个自定义基础控制器类,但它可能适用于简单场景)或另一个临时的每个请求存储。

然后,您需要创建一个Web API操作过滤器。它类似于常规的ASP.NET MVC动作过滤器,网上有很多教程,但大多数都是关于授权的。

此过滤器会尝试将API密钥从请求中注入控制器或您选择的临时存储器 - 在过滤器的OnActionExecutingmethod中,您可以访问请求信息和控制器上下文。

完成后,只需在Web API配置中注册您的过滤器,这里是一个example关于如何做到这一点。