2014-01-16 54 views
1

當用戶通過身份驗證時,我想阻止他更新/刪除/讀取從其他帳戶創建的數據......通過告訴他您沒有權限403!在AuthorizeFilter中獲取api控制器構造函數的值

獲取ISchoolyearService實例調用其HasUserPermission()方法的最佳方式是什麼?

我知道我可以在這裏新建SchoolyearService,但這會在我的應用程序中完全無法使用IoContainer。

​​

回答

0

好吧我終於找到了如何從當前請求獲得ISchoolyearService :

從DependencyScope獲取註冊服務!

現在這個屬性應該直接放在控制器上。它不需要把它放在動作上,因爲我做的http動詞中的if/else。

bool canUserExecuteAction = false; 
if (actionContext.Request.Method == HttpMethod.Put) 
{ 
    int targetId = Convert.ToInt32(actionContext.Request.GetRouteData().Values["Id"]); 
    int userId = actionContext.Request.Content.ReadAsAsync<SchoolyearEditRequest>().Result.Schoolyear.UserId; 
    var requstScope = actionContext.ControllerContext.Request.GetDependencyScope(); 
    var service = requstScope.GetService(typeof(ISchoolyearService)) as ISchoolyearService; 
    canUserExecuteAction = service.HasUserPermission(userId, targetId); 

    if (canUserExecuteAction) 
    { 
     base.OnAuthorization(actionContext); 
    } 
    else 
    { 
     actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden); 
    } 
} 
0

如果您在SchoolyearController作出_Service參數公開,你可以嘗試這樣的事情在OnAuthorization方法:

var schoolyearController = actionContext.ControllerContext.Controller as SchoolyearController; 
canUserExecuteAction = schoolyearController._service.HasUserPermission(userId, schoolyearId); 
相關問題