asp.net-mvc – MVC 3 – 仅限特定用户访问
发布时间:2020-12-16 06:47:10 所属栏目:asp.Net 来源:网络整理
导读:在我的Web应用程序中,注册用户可以添加新内容并在以后进行编辑.我只希望内容的作者能够编辑它.除了在检查记录的用户是否与作者相同的所有操作方法中手动编写代码之外,还有其他智能方法吗?我可以用于整个控制器的任何属性? 解决方法 Any attribute that I c
在我的Web应用程序中,注册用户可以添加新内容并在以后进行编辑.我只希望内容的作者能够编辑它.除了在检查记录的用户是否与作者相同的所有操作方法中手动编写代码之外,还有其他智能方法吗?我可以用于整个控制器的任何属性?
解决方法
是的,您可以使用自定义属性扩展Authorize属性: public class AuthorizeAuthorAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { // the user is either not authenticated or // not in roles => no need to continue any further return false; } // get the currently logged on user var username = httpContext.User.Identity.Name; // get the id of the article that he is trying to manipulate // from the route data (this assumes that the id is passed as a route // data parameter: /foo/edit/123). If this is not the case and you // are using query string parameters you could fetch the id using the Request var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string; // Now that we have the current user and the id of the article he // is trying to manipualte all that's left is go ahead and look in // our database to see if this user is the owner of the article return IsUserOwnerOfArticle(username,id); } private bool IsUserOwnerOfArticle(string username,string articleId) { throw new NotImplementedException(); } } 然后: [HttpPost] [AuthorizeAuthor] public ActionResult Edit(int id) { ... perform the edit } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-core – Asp.Net 5 MVC 6 Startup.cs Beta8中的程序
- asp.net – 将WPF转换为Web
- asp.net-mvc – MVC3中Textbox的水印
- asp.net-mvc-3 – 用于ASP.NET MVC的Razor View Engine的源
- 如何在ASP.NET中获取服务器端的输入值(类型文本)?
- asp.net – 为什么当试图保存更改时,GridView行“null”的D
- asp.net-mvc – ASP.NET MVC ViewData和视图模型的最佳实践
- asp.net – Fiddler:错误502代理错误
- 多线程异步编程示例和实践-Thread和ThreadPool
- asp.net-mvc – 使用Castle Windsor在ASP.NET MVC中实现多租
推荐文章
站长推荐
- asp.net-mvc – 传递的JSON集合未被控制器拾取
- ASP.NET – ActionResult参数在传递字符串时总是
- asp.net-mvc-3 – Asp.net mvc 3-获取当前控制器
- asp.net-mvc – ASP.NET在基本控制器中重定向
- ASP.NET显示SVN版本号
- asp.net – Visual Studio 2010图表控件 – 线条
- 如何从ASP .NET网站检测客户端上安装的Java运行时
- asp.net-mvc-4 – 我应该如何使用ReturnUrl = Vi
- ASP.NET <%=%> vs <%:%>
- asp.net-mvc – ASP.net MVC – 视图如何访问模型
热点阅读