Asp.net mvc 2 MVC2 C#基于ID限制对视图的访问
我有两个表,一个是作业表,一个是经理表,当作业ID传递到视图“详细信息”时,可以访问该作业的详细信息Asp.net mvc 2 MVC2 C#基于ID限制对视图的访问,asp.net-mvc-2,authentication,forms-authentication,Asp.net Mvc 2,Authentication,Forms Authentication,我有两个表,一个是作业表,一个是经理表,当作业ID传递到视图“详细信息”时,可以访问该作业的详细信息 Job_id Job_Title Manager_id 23 Chimney Sweep 65 24 Rat Catcher 84 Managers Email 65 arthur@work.com 66 fred@work.com 我想根据经理的电子邮件限制对视图的访问-例如,如果我们在,那么只有art
Job_id Job_Title Manager_id
23 Chimney Sweep 65
24 Rat Catcher 84
Managers Email
65 arthur@work.com
66 fred@work.com
我想根据经理的电子邮件限制对视图的访问-例如,如果我们在,那么只有arthur可以访问该视图。。将使用广告来挑选用户的电子邮件
任何指点都将不胜感激 您可以编写自定义模型活页夹:
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);
}
}
自定义模型活页夹也可以在应用程序\u 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和数据库通信时,可能需要这些依赖项。谢谢,这看起来是一个不错的方法,可以尝试一下了!:)