c# - 如果当前用户不属于 [Authorize] 所需的角色,我可以自动重定向他们吗?

标签 c# asp.net asp.net-mvc asp.net-membership authorize-attribute

在我正在构建的 ASP.NET MVC 站点中,我有一些方法,其中使用它们的用户必须处于特定角色(碰巧,如果他们不是,则意味着他们被暂停网站)。为实现这一点,我使用 [Authorize(Roles="RoleName")] 属性没有任何困难。

但是,我不太明白没有通过 [Authorize] 检查的用户会怎样?它们显示了什么?

如果暂停的用户尝试使用这些方法,我想将他们重定向到不同的操作。目前,我一直在使用空白的 [Authorize] 属性(未指定任何角色),然后在操作代码中检查用户是否属于该角色。

我的方法对我来说就像代码的味道。 如果用户未通过 [Authorize] 检查,是否可以指定向用户显示的内容(或将他们重定向到的位置)?

最佳答案

AuthorizeAttribute MSDN page 中所述:

If an unauthorized user tries to access a method that is marked with the Authorize attribute, the MVC framework returns a 401 HTTP status code. If the site is configured to use ASP.NET forms authentication, the 401 status code causes the browser to redirect the user to the login page.

如果您正在使用表单例份验证并希望重定向到登录页面,则您无事可做。否则实现您自己的 IAuthorizationFilter 来进行重定向。

编辑:参见this blog post这基本上是通过自定义重定向手动重新实现 AuthorizeAttribute。

关于c# - 如果当前用户不属于 [Authorize] 所需的角色,我可以自动重定向他们吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3079737/

相关文章:

c# - 使用带有后续 try-finally 子句的 ReaderWriterLockSlim.EnterXXX() 模式是否完全安全

c# - 使用 asp.net C# 通过 GSM 调制解调器发送短信

javascript - 在 ASP.NET WebForms 服务器端帖子之间持续 knockout ViewModel ...

c# - fb like 按钮有什么问题?

c# - asp.net 在部分 View 中使用与其父 View 不同的模型?

jquery - 使用 Bootstrap Modal 通过 MVC5/razor 显示 View

asp.net-mvc - 如何在 ajax 请求 $.get/$.post 运行时显示模态 Loading ...?

c# - Mage.exe 不为 4.5 生成兼容的框架

c# - LINQ to Entities - 更新二进制字段

c# - Roslyn 中的简单代码完成示例