如何在ASP中显示授权错误消息。净MVC 2应用程序?

时间:2021-08-13 05:35:40

I'm using the Authorize attribute to filter controller actions based on user roles, but if an unauthorized action is attempted, the user is redirected back to the login page. As I user I would find this confusing and irritating.

我正在使用Authorize属性根据用户角色筛选控制器操作,但是如果尝试了未经授权的操作,用户将被重定向回登录页面。当我使用它的时候,我会感到困惑和愤怒。

How can I instead show an error message informing the user they need certain roles, and remain on the view where they attempted an action?

相反,我如何显示一条错误消息,通知用户他们需要某些角色,并保持在他们尝试操作的视图中呢?

2 个解决方案

#1


2  

You will need to write a custom Authorize attribute which doesn't return a HttpUnauthorizedResult. Also remaining on the same view will be a difficult task as you might need to keep all the context after the request.

您将需要编写一个自定义授权属性,该属性不返回HttpUnauthorizedResult。保持相同的视图也是一项困难的任务,因为您可能需要在请求之后保持所有上下文。

#2


0  

The solution I found so far is you need to save a session for the current page in _ViewStart (maybe something else in MVC2), then use that in your custom authorization class to redirect to the page and show the message.

到目前为止,我发现的解决方案是需要为_ViewStart中的当前页面保存一个会话(可能是MVC2中的其他内容),然后在自定义授权类中使用该会话重定向到页面并显示消息。

#1


2  

You will need to write a custom Authorize attribute which doesn't return a HttpUnauthorizedResult. Also remaining on the same view will be a difficult task as you might need to keep all the context after the request.

您将需要编写一个自定义授权属性,该属性不返回HttpUnauthorizedResult。保持相同的视图也是一项困难的任务,因为您可能需要在请求之后保持所有上下文。

#2


0  

The solution I found so far is you need to save a session for the current page in _ViewStart (maybe something else in MVC2), then use that in your custom authorization class to redirect to the page and show the message.

到目前为止,我发现的解决方案是需要为_ViewStart中的当前页面保存一个会话(可能是MVC2中的其他内容),然后在自定义授权类中使用该会话重定向到页面并显示消息。