我有一个 ASP.NET MVC 网站,我在其中建立了一个权限系统。例如,当当前用户没有足够的权限时,有些链接会被隐藏。但是,如果他们手动输入该链接的 URL,他们仍然可以访问内容。
我知道我可以使用 [Authorize]
属性来阻止没有正确用户角色的用户,但是我如何实现我自己的属性来阻止不符合自定义要求的用户的操作,无需在每个操作中编写手动检查?
最佳答案
您可以编写自定义 Authorize
属性并覆盖 AuthorizeCore
方法,您可以在其中放置自定义授权逻辑:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authroized = base.AuthorizeCore(httpContext);
if (!authroized)
{
return false;
}
// at this stage the base authorization process has passed.
// now implement your custom authorization logic and return true or false
// here you have access to the HttpContext and as a consequence to all
// request and route parameters so you could implement any
// authorization logic you want
// And of course if you want a completely custom authorization logic
// ignoring the base functionality don't call the base method above
// but completely override anything here
}
}
现在剩下的就是用这个自定义属性装饰相应的 Controller / Action 。
关于c# - 限制对 MVC 操作的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11091235/