asp.net-mvc-3 – 具有MVC3的多用户应用程序,ASP.NET成员资格 –
发布时间:2020-12-16 03:28:37 所属栏目:asp.Net 来源:网络整理
导读:我正在使用ASP.NET MVC3和EF4构建一个简单的多用户(多租户?)应用程序,一个数据库,一个代码库,所有用户使用相同的URL访问应用程序.一旦用户登录,他们应该只能访问他们的数据,我使用默认的asp.NET成员资格提供程序,并在每个数据表上添加了“UserId”Guid字段.
我正在使用ASP.NET MVC3和EF4构建一个简单的多用户(多租户?)应用程序,一个数据库,一个代码库,所有用户使用相同的URL访问应用程序.一旦用户登录,他们应该只能访问他们的数据,我使用默认的asp.NET成员资格提供程序,并在每个数据表上添加了“UserId”Guid字段.显然,我不希望用户A对用户B的数据有任何访问权限,因此我几乎在控制器上的每个操作中都添加了以下内容.
public ActionResult EditStatus(int id) { if (!Request.IsAuthenticated) return RedirectToAction("Index","Home"); var status = sService.GetStatusById(id); // check if the logged in user has access to this status if (status.UserId != GetUserId()) return RedirectToAction("Index","Home"); . . . } private Guid GetUserId() { if (Membership.GetUser() != null) { MembershipUser member = Membership.GetUser(); Guid id = new Guid(member.ProviderUserKey.ToString()); return id; } return Guid.Empty; } 这种重复肯定是错误的,必须有一种更优雅的方式来确保我的用户无法访问彼此的数据 – 我缺少什么? 解决方法
自定义模型绑定器: public class StatusModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { // Fetch the id from the RouteData var id = controllerContext.RouteData.Values["id"] as string; // TODO: Use constructor injection to pass the service here var status = sService.GetStatusById(id); // Compare whether the id passed in the request belongs to // the currently logged in user if (status.UserId != GetUserId()) { throw new HttpException(403,"Forbidden"); } return status; } private Guid GetUserId() { if (Membership.GetUser() != null) { MembershipUser member = Membership.GetUser(); Guid id = new Guid(member.ProviderUserKey.ToString()); return id; } return Guid.Empty; } } 然后你会在Application_Start中注册这个模型绑定器: // Could use constructor injection to pass the repository to the model binder ModelBinders.Binders.Add(typeof(Status),new StatusModelBinder()); 最后 // The authorize attribute ensures that a user is authenticated. // If you want it to redirect to /Home/Index as in your original // example if the user is not authenticated you could write a custom // Authorize attribute and do the job there [Authorize] public ActionResult EditStatus(Status status) { // if we got that far it means that the user has access to this resource // TODO: do something with the status and return some view ... } 结论:我们已经把这个控制器放在饮食控制器应该是这样的方式:-) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- mvc项目架构搭建之UI层的搭建 架构搭建初步
- asp.net-mvc-4 – 如何输出Request.CreateResponse方法的js
- asp.net-mvc – 在我的asp.net MVC解决方案中保持脚本文件夹
- ASP.NET测量性能
- asp.net – 在LINQ-to-SQL中运行映射存储过程方法时生成的奇
- asp.net – 从SQL 2005 Server访问TimeZoneInfo
- asp.net-mvc-3 – 如何根据当前页面和/或主页在Orchard CMS
- asp.net – 如何在SSRS公式字段中按两个日期计算天数
- asp.net – 在Azure Compute Emulator之外运行DiagnosticMo
- 实体框架 – 对ASP.NET MVC Onion架构的意见