2011-02-20 43 views
2

我有兩個表格,一個是帶有管理者的作業,當一個作業ID被傳遞給視圖'Detail'時,該作業的詳細信息是可訪問的。MVC2 C#根據ID限制訪問視圖

Job_id Job_Title  Manager_id 
23  Chimney Sweep 65 
24  Rat Catcher  84 

Managers Email 
65   [email protected] 
66   [email protected] 

我想限制訪問基於該MANAGER_EMAIL的觀點 - 如果我們在http://jobsite/jobs/Detail/23那麼只有亞瑟可以訪問視圖,例如..將使用AD挑選出用戶的電子郵件..

任何指針將不勝感激!

回答

4

你可以寫一個自定義的模型綁定:

public class JobModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     // fetch the job id from the request 
     var jobId = controllerContext.RouteData.Values["id"]; 

     // fetch the currently connected username 
     string user = controllerContext.HttpContext.User.Identity.Name; 

     // Remark: You might need an additional step here 
     // to query AD and fetch the email 

     // Given the job id and the currently connected user, try 
     // to fetch the corresponding job 
     Job job = FetchJob(jobId, user); 

     if (job == null) 
     { 
      // We didn't find any job that corresponds to 
      // the currently connected user 
      // => we throw 
      throw new HttpException(403, "Forbidden"); 
     } 
     return job; 
    } 

    private Job FetchJob(int jobId, string user) 
    { 
     throw new NotImplementedException(); 
    } 
} 

,然後讓你的控制器:

public class JobsController : Controller 
{ 
    [Authorize] 
    public ActionResult Show([ModelBinder(typeof(JobModelBinder))]Job job) 
    { 
     return View(job); 
    } 
} 

定製模型綁定也可以在Application_Start註冊:

protected void Application_Start() 
{ 
    ... 
    ModelBinders.Binders.Add(typeof(Job), new JobModelBinder()); 
} 

這將簡化您的控制器操作:

public class JobsController : Controller 
{ 
    [Authorize] 
    public ActionResult Show(Job job) 
    { 
     // If we get to that point it means that the 
     // currently connected user has the necessary 
     // permission to consult this view. The custom 
     // model binder would have populated the Job model 
     // and we can safely pass it to the view for display 
     return View(job); 
    } 
} 

此方法的另一個優點是可以將依賴關係注入到自定義模型聯編程序的構造函數中。當嘗試與AD和數據庫進行通信時,可能需要這些依賴關係。

+0

謝謝,看起來像一個很好的方法,去給它一去! :) – beebul