使用ASP.NET MVC重定向到FormsAuthentication登录页面时显示有用的消息

una*_*age 2 asp.net-mvc forms-authentication authorize-attribute http-status-code-401

我想制作一个AuthorizeAttribute包含Message属性的自定义.问题是,我的FormsAuthentication重定向到指定的loginUrl.该视图如何访问属性的Message属性?

例如,我使用自定义AuthorizeAttribute进行此操作

[Authorize(Message="You must be logged in to see user settings.")]
public ActionResult Settings()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

FormsAuthentication如果用户没有登录,它会被重定向到/ Account/LogOn(感谢web.config中的设置).我想在LogOn View上显示"您必须登录才能看到用户设置",以便用户知道为什么他们被重定向到LogOn页面

Rya*_*and 5

一种选择是将Message属性的值放入自定义AuthorizeAttribute的HandleUnautherizeRequest方法中的TempData中.然后在您的帐户控制器上的LogOn操作中,从TempData中获取值并将其放入ViewBag或您的模型中,以便View可以访问它.

AuthorizeAttribute:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{            
    base.HandleUnauthorizedRequest(filterContext);
    filterContext.Controller.TempData["MessageFromMyAttribute"] = this.Message;
}
Run Code Online (Sandbox Code Playgroud)

的AccountController

public ActionResult LogOn()
{
    ViewBag.AttributeMessage = TempData["MessageFromMyAttribute"];
    return View();
}
Run Code Online (Sandbox Code Playgroud)

因为MVC在幕后进行重定向,所以TempData中的值将在重定向中持续存在.