I want to make a custom AuthorizeAttribute that includes a Message property. The problem is, my FormsAuthentication redirects to the specified loginUrl. How can that View get access to the attribute’s Message property?
for example, I have this action using my custom AuthorizeAttribute
[Authorize(Message="You must be logged in to see user settings.")]
public ActionResult Settings()
{
return View();
}
which gets redirected to /Account/LogOn (thanks to the FormsAuthentication settings in web.config) if the user is not logged in. I want to show the “You must be logged in to see user settings” on the LogOn View so the user knows why they were redirected to the LogOn page
One option would be to put the value of your Message property into TempData in the HandleUnautherizeRequest method of your custom AuthorizeAttribute. Then in the LogOn action on your Account controller take the value from TempData and put it into the ViewBag or your model so that the View has access to it.
AuthorizeAttribute:
AccountController
Because MVC is doing a redirect behind the scenes the value in TempData will persist across the redirect.