Displaying a useful message when redirected to FormsAuthentication logon page with ASP.NET MVC
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()
{
开发者_Go百科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:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
filterContext.Controller.TempData["MessageFromMyAttribute"] = this.Message;
}
AccountController
public ActionResult LogOn()
{
ViewBag.AttributeMessage = TempData["MessageFromMyAttribute"];
return View();
}
Because MVC is doing a redirect behind the scenes the value in TempData will persist across the redirect.
Do the following:
- Create your own attribute, that inherits from
AuthorizeAttribute
- In your filter, add the message to
TempData
- In the action that you redirect to when login is required, get the message from
TempData
and pass it to the view.
精彩评论