2011-02-20 80 views
2

私は、ジョブIDがビュー '詳細'に渡されたときに、ジョブの詳細がアクセス可能なときに、マネージャーと1つのジョブで2つのテーブルを持っています。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); 
    } 
} 

このアプローチのもう1つの利点は、カスタムモデルバインダーのコンストラクターに依存性を注入できることです。 ADとデータベースと通信しようとすると、これらの依存関係が必要になることがあります。

+0

おかげで、良いアプローチのように見えます。 :) – beebul

関連する問題