2013-08-01 4 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'와 같은 필수 매개 변수의 경우 authenticate 메소드에서 BaseController 또는 ActionFilter를 사용하여 유효성을 검사합니다. 나중에 apikey에 대한 액세스가 필요한 경우 항상 존재한다고 가정 할 수 있습니다. 필터가 apikey를 Context.Items 컬렉션이나 원하는 경우 비슷한 것으로 푸시하도록 할 수도 있습니다. –

답변

1

먼저 액션의 본문에서 API 키를 검색하는 정확한 방법을 결정해야합니다. 메서드의 인수로 전달하고 싶지 않으므로 컨트롤러의 속성이 될 수 있습니다 (이 작업을 수행하는 가장 좋은 방법은 아니며 사용자 지정 기본 컨트롤러 클래스를 만들어야하지만 간단한 시나리오에서 작동 할 수도 있음)) 또는 다른 임시 요청 별 저장 영역.

그런 다음 웹 API 조치 필터를 작성해야합니다. 그것은 일반적인 ASP.NET MVC 액션 필터와 유사합니다. 많은 웹 튜토리얼이 있지만 대부분은 인증에 관한 것입니다.

이 필터는 요청의 API 키를 원하는 컨트롤러 또는 임시 저장소에 삽입하려고 시도합니다. 필터의 OnActionExecutingmethod 안에 요청 정보와 컨트롤러 컨텍스트 모두에 대한 액세스 권한이 있습니다.

모두 완료되면 웹 API 구성에 필터를 등록하십시오. 여기에 example이 있습니다.

관련 문제