views:

33

answers:

1

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.

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?

+1  A: 

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.

Darin Dimitrov
Ouch! Could I maybe return a custom HttpUnauthorizedResult that is routed to an error view, rather than the login view, and provide an ActionLink on the error view back to the starting view?
ProfK
Writing a cusom 'Authorize' attribute is a lot easier than you think, and it is the cleanest way to deal with your situation, and it is also re-useable throughout your project.
Saajid Ismail
@Profk, if you want to be routed to an error view either `Response.Redirect`, or return `ViewResult` inside the filter.
Darin Dimitrov
@Saajid, I'm it is quite easy, but I always think too much, like redirecting back to the original view with some kind of directive to display a model popup with error advice. I'll stick to an error view for now.
ProfK
@Darin, I'm afraid I have now idea where to begin implementing your suggestion. I know it's in my custom attribute, but how would I do Response.Redirect, or, how would my Viewresult return know where to go?
ProfK
Using Response.Redirect is counter-productive to the whole concept of ASP.Net MVC. I don't recommend it.
Saajid Ismail