Display a special authorization message for the [Authorize] attribute

Is there a way to display an authorization message for a specific action if the [Authorize] or [Authorize(Roles="Administrator")] attribute redirects the user to the login page?

Perfectly,

 [Authorize(Roles="Administrator", Message="I'm sorry Dave. I'm afraid I can't let you do that.")] public ActionResult SomeAdminFunction() { // do admin stuff return View(); } 

As I understand it, attributes are not intended to add functionality, but this seems to be purely informative. You could have done this inside the action, but it seems inelegant compared to using the attribute.

As an alternative,

 if (!Request.IsAuthenticated) { if (!User.IsInRole("Administrator")) SetMessage("You need to be an administrator to destroy worlds."); // write message to session stack return RedirectToAction("SignIn", "Account"); } 

Is there an existing way to do this, or do I need to override the [Authorize] attribute?

+4
source share
1 answer

I would override the attribute to add my specific message.

+2
source

Source: https://habr.com/ru/post/1306820/


All Articles